zoukankan      html  css  js  c++  java
  • 15. Vue2.4+新增属性.sync

    .sync

    在vue2.4以前,父组件向子组件传值用props;子组件不能直接更改父组件传入的值,需要通过$emit触发自定义事件,通知父组件改变后的值。

    父组件:

    <template>
      <div>
          <p>父组件传入子组件的值:{{name}}</p>
        <fieldset>
          <legend>子组件</legend>
          <child :val.sync="name">
          </child>
        </fieldset>
      </div>
    </template>
    
    <script>
    import child from './child';
    export default {
        components:{child},
        data: function () {
            return {
                name:'hello'
            }
         },
        methods: {
            
        }
    }
    </script>
    
    <style>
    
    </style>

    子组件:

    <template>
      <div style="margin-top: 300px;margin-left: 500px;">
        <label class="child">
            输入框:
           <input :value=val @input="$emit('update:val',$event.target.value)"/>
        </label>
      </div>
    </template>
    
    <script>
    export default {
        name:'child',
        props:{
            val:String
        },
        data()  {
            return {
            }
        },
        methods: {
        }
    }
    </script>
    
    <style>
    
    </style>

    写法上简化了一部分,很明显父组件不用再定义方法检测值变化了。其实只是对以前的$emit方式的一种缩写,.sync其实就是在父组件定义了一update:val方法,来监听子组件修改值的事件。

    参考:https://www.jianshu.com/p/4649d317adfe

  • 相关阅读:
    十万个为什么
    安装VmwareTools遇到的问题
    CentOS7没有ifconfig命令怎么办
    ftp/ http/ https/ tcp的关系
    C/S和B/S架构
    Nginx 安装以及验证教程
    osi七层模型
    在linux上安装tenginx
    Awvs、Snort的下载安装
    Laravel——DI(依赖注入)
  • 原文地址:https://www.cnblogs.com/shix0909/p/11217591.html
Copyright © 2011-2022 走看看