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

  • 相关阅读:
    grid 布局
    mongoose
    Nestjs 上传文件
    Nestjs 设置静态文件,public
    Centos 为Nginx 搭建https
    react组件
    namecheap 添加二级域名
    electron+react
    遍历文件,读取.wxss文件,在头部添加一条注释
    react 中的绑定事件
  • 原文地址:https://www.cnblogs.com/shix0909/p/11217591.html
Copyright © 2011-2022 走看看