zoukankan      html  css  js  c++  java
  • Vue父子组件双向绑定传值的实现方法

    从某方面讲,父组件传值给子组件进行接收,之后在子组件中更改是不允许的。你会发现vue也会直接报错,而在封装一些组件的时候,又希望做到数据的双向绑定,可以更好的控制与使用,在网上找到了两种方法,一种的话是使用 v-model 还有一种是 .sync
    这里我推荐使用.sync

    原因:v-mode只能进行单个双向绑定值而使用.sync可支持多个双向绑定值,当然,具体使用哪个可以参照自己的使用场景来区分

    这里我就来写个通过.sync 实现父子数据双向绑定的例子

    代码如下:

    这是父组件

    vi设计http://www.maiqicn.com 办公资源网站大全https://www.wode007.com

    <template>
      <div class="home">
        <!-- 此处只需在平时常用的单向传值上加上.sync修饰符 -->
        <HelloWorld :msg.sync="parentMsg" :msg2.sync="parentMsg2" />
      </div>
    </template>
    
    <script>
    import HelloWorld from '@/components/HelloWorld.vue'
    
    export default {
        name: 'home',
        data(){
            return{
                parentMsg:'test',
                parentMsg2:'test2'
            }
        },
        watch:{
            // 监听数据的变化输出 newV 改变的值,oldV 改变之前的值
            parentMsg(newV,oldV){
                console.log(newV,oldV);
            },
            parentMsg2(newV,oldV){
                console.log(newV,oldV);
            }
        },
        components: {
            HelloWorld
        }
    }
    </script>
    
    

    子组件

    <template>
        <div>
            <h1>{{ msg }}</h1>
            <h1>{{ msg2 }}</h1>
            <button @click="fn()">点击</button>
        </div>
    </template>
    <script>
     
    export default{
        props:{
            msg:String,
            msg2:String
            
        },
        methods:{
            fn(){
                let some = '张三';
                let some2 = '李四';
                // 将这个值通过 emit
                // update为固定字段,通过冒号连接双向绑定的msg,将some传递给父组件的v-model绑定的变量
                this.$emit('update:msg',some);
                this.$emit('update:msg2',some2);
            }
        }
    }
    </script>
    

    此处需要注意,虽然加上 .sync 即可双向绑定,但是还是要依靠子组件 $emit 去触发 update:prop名 实现修改父组件的变量值实现双向数据流,如果直接对prop的属性直接赋值,依然会出现报错。

    事实上, .sync 修饰符是一个简写,它做了一件事情

    <template>
     <HelloWorld :msg.sync="parentMsg" :msg2.sync="parentMsg2" />
     <!-- 等价于 -->
     <HelloWorld :msg="parentMsg" @updata:msg="parentMsg = $event"></HelloWorld>
     <!-- 这里的$event就是子组件$emit传递的参数 -->
    </template>
  • 相关阅读:
    依赖单元测试开发
    今天晚上的遭遇
    设计,UML,测试驱动开发
    我是LIGHT的LP,今天由我代笔
    转贴一篇关于BitVector32的Blog
    看牙记
    调整过的书籍目录
    Queue和Stack的学习代码
    BitVector32结构学习
    Visual Studio 2008 在64位操作系统上调试代码的解决方式
  • 原文地址:https://www.cnblogs.com/xiaonian8/p/13714388.html
Copyright © 2011-2022 走看看