prop是父组件向子组件进行传值,而必须借助emit,才能将子组件的值传递到父组件。
那么,一个子组件,如果在多个不同的组件中都在引用。要实现数据的双向绑定,要怎么做呢??→ v-model!
v-model是能够真正实现双向数据绑定的方法,也是多个子父组件之间进行通信的好手段:
子组件:
<template> <div> 测试v-model双向数据绑定的父子组件通信 <label >绑定的值:<input type="text" v-model="inputValue" :key="Math.random() * 10" /><el-button @click="clickBtn" >确定</el-button ></label > <br />
<!-- 当在父组件中修改input框中的值时,inputValue会同步显示在这个位置,即父子组件实现了双向绑定 -->
<label>子组件中测试: {{ inputValue }}</label> </div> </template> <script> export default { name: 'test-v-model', model: { prop: 'inputValue', // 父组件在引用该组件时,父组件中的v-model值,就会传给它,这是一个可以自定义的量 event: 'inputChange', // 意思是:当子组件中emit执行inputChange事件时,相当于执行了input的event事件 }, props: { inputValue: { type: String, default: 'testttt', }, }, data() { return { getValue: '', } }, watch: { inputValue: { handler(newVal) { console.log('子组件中监听:', newVal) }, }, }, methods: { clickBtn() { this.$emit('inputChange', this.inputValue) // 点击子组件中的按钮,通过前面定义的inputChange时间,将model里的inputValue值传给父组件 }, }, } </script>
父组件:
<template> <div class="configSearch"> <-- 直接引用子组件 --> <test-vmodel v-model="testValue1" @inputChange="inputChange"></test-vmodel> <el-card class="card-2"> <-- 子组件modifyConfigDialog中引用子组件 --> <modify-config-dialog v-model="testValue2"></modify-config-dialog> </el-card> </div> </template> <script> import testVmodel from './testVmodel' export default { components: { testVmodel }, data() { return { testValue1: '', testValue2: '', } }, mounted() {}, methods: { inputChange(v) { console.log('父组件中:', v) // 第一个直接引用的子组件添加了子组件中定义的inputChange事件,点击时,这里会打印出来输入框中的值 }, }, } </script>
测试以上组件的引用发现:多处引用的这同一个组件,在改变第一处引用的子组件时不会引起第二个子组件值的变化,同理,改变第二个子组件值时,也不会影响第一个子组件的输入框
所以,在出现同一个子组件被多处引用时,实现双向数据绑定,请使用v-model,省时省力!简单易行!加油
最后,
这才是面试时被问到组件复用如何实现子父组件通信时的正确答案,而不是prop和emit,那只是一种组件间的传值谢谢。通信用v-model是好实现的~ 或者使用vue的state状态管理(但没有这个方便~ 或者eventBus~~)