0


Vue 父子组件实现数据双向绑定效果的两种方式

方式一:通过监听事件实现

父组件将数据传递给子组件通过 props 实现;而子组件将数据传递给父组件通过事件来实现,在子组件中定义一个事件,在该事件中传递值,由父组件中监听这个事件。通过这种方式实现父子组件双向绑定的效果最常见。

子组件案例代码:

<template><el-selectv-model="value"placeholder="请选择"@change="change"><el-optionv-for="item in options":key="item.value":label="item.label":value="item.value"></el-option></el-select></template><script>exportdefault{name:'sonTest',// props 下定义父组件传递给子组件的数据props:{// 父组件使用子组件时通过 :options 传递给子组件options:{type: Array,default:[]}},data(){return{value:''}},methods:{change(){
        console.log('子组件下拉框值发生改变:',this.value)// 当下拉框中选定的值发生改变后,通过 $emit 回调 update 事件,并将修改后的值返回给父组件this.$emit('update',this.value)// 触发父组件的 @update 事件// 父组件使用子组件时通过 @update 指定回调的处理方法}}}</script><stylescoped></style>

父组件案例代码:

<template><son-test:options="options"@update="update"></son-test></template><script>import SonTest from'./sonTest'exportdefault{name:'fatherTest',components:{ SonTest },data(){return{value:'',options:[{value:'选项1',label:'黄金糕'},{value:'选项2',label:'双皮奶'},{value:'选项3',label:'蚵仔煎'},{value:'选项4',label:'龙须面'},{value:'选项5',label:'北京烤鸭'}],}},methods:{update(newValue){// 与 value 实现双向绑定效果this.value = newValue
        console.log('子组件通过事件传递过来的值:', newValue)},}}</script><stylescoped></style>

优点:可以实现父子组件多个值的双向绑定效果。

缺点:父组件需要编写监听子组件事件的代码。

方式二:通过 v-model 实现

在子组件中指定 model 变量,父组件中通过 v-model 指令来实现双向绑定,通过这种方式父组件无需监听子组件的事件。

子组件案例代码:

<template><el-selectv-model="sonValue"placeholder="请选择"><el-optionv-for="item in options":key="item.value":label="item.label":value="item.value"></el-option></el-select></template><script>exportdefault{name:'sonTest',// props 下定义父组件传递给子组件的数据props:{// 父组件使用子组件时通过 :options 传递给子组件options:{type: Array,default:[]},value:{type: String,default:''}},model:{// 需要双向绑定的 props 变量名称,也就是父组件通过 v-model 与子组件双向绑定的变量prop:'value',// 定义由 $emit 传递变量的名称event:'newValue'},data(){return{// 子组件不能修改 props 下的变量,所以定义一个临时变量sonValue:this.value
      }},watch:{// 监听 sonValue 临时变量,如果临时变量发生变化,那么通过 $emit 将新的值传递给父组件sonValue(value){
        console.log('子组件下拉框值发生改变:',this.sonValue)// 【注意】newValue x需要和 model.event 定义的值一致this.$emit('newValue',this.sonValue)}}}</script><stylescoped></style>

父组件案例代码:

<template><son-test:options="options"v-model="value"></son-test></template><script>import SonTest from'./sonTest'exportdefault{name:'fatherTest',components:{ SonTest },data(){return{value:'选项1',options:[{value:'选项1',label:'黄金糕'},{value:'选项2',label:'双皮奶'},{value:'选项3',label:'蚵仔煎'},{value:'选项4',label:'龙须面'},{value:'选项5',label:'北京烤鸭'}],}},watch:{// 下面这个监听只是为了打印显示value(newValue){
        console.log('value 值发生改变:', newValue)}}}</script><stylescoped></style>

优点:父组件无需编写额外的代码,直接通过 v-model 实现双向绑定。

缺点:这种方式只能双向绑定一个值。


本文转载自: https://blog.csdn.net/weixin_44496396/article/details/125166943
版权归原作者 shijialeya. 所有, 如有侵权,请联系我们删除。

“Vue 父子组件实现数据双向绑定效果的两种方式”的评论:

还没有评论