最近在封装组件,我整理了一些封装方法,感谢我司的前端团队,若是还有更好的方法,欢迎来稿,欢迎切磋。前端
vue的v-model是一个十分强大的指令,它能够自动让input里的值自动和你设定的值进行绑定,它是如何实现的呢?vue
1.语法糖:使用v-model来进行数据双向绑定以下:this
<input v-model="ying">
2.其实是这样实现的:双向绑定
<input v-bind:value="ying" v-on:input="ying=$event.target.value"> <a-input v-bind:value="ying" v-on:input="ying=arguments[0]"></a-input>
3.其实v-model只不过是一个语法糖而已,真正的实现靠的仍是code
(1) v-bind:绑定响应式数据
(2) 触发 input 事件 并传递数据 (重点)对象
父子组件通讯,都是单项的,不少时候须要双向通讯。方法以下:事件
(1)使用syncip
父组件:get
<a-input :value.sync="text" ></a-input>
子组件:input
<template> <div> <input v-model="currentValue" @input="handleModelInput"> </div> </template> <script> export default { props: { value: [String,Number,Date], }, methods: { handleModelInput() { this.$emit("update:value", this.currentValue); } }, watch: { value(newValue) { this.currentValue = newValue } </script>
(2)使用v-model 子组件触发 input 事件 并传递数据,并对value进行监听
父组件:
<a-input v-model="text">
子组件:
<input v-model="currentValue" @input="handleModelInput"> props:{ value:[String,Number], } handleModelInput() { this.$emit('change',this. currentValue) } watch: { value(newValue) { this.currentValue = newValue } },
(3)使用model prop属性 even事件change
父组件:
<a-input v-model="text">
子组件: <template> <div> <input v-model="currentValue" @input="handleModelInput"> </div> </template> <script> export default { model: { prop: 'value', event: 'change' }, props: { value:[String,Number], }, methods: { handleModelInput() { this.$emit('change', this.currentValue) } }, watch: { value(newValue) { this.currentValue = newValue } } </script>
码字辛苦,文章如对您有帮助,麻烦支持点赞~