vue中的.sync修饰符

vue中的.sync修饰符

在Vue中,子父组件最常用的通信方式就是通过props进行数据传递,props值只能在父组件中更新并传递给子组件,在子组件内部,是不允许改变传递进来的props值,这样做是为了保证数据单向流通。但有时候,我们会遇到一些场景,需要在子组件内部改变props属性值并更新到父组件中,这时就需要用到.sync修饰符。

在下面demo中,通过定义一个Child子组件并设置name属性来显示一句欢迎语,当点击按钮时,通过在父组件中来改变name属性的值;当点击欢迎语时,则通过在Child子组件中改变name属性值。

没有.sync修饰符时

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>.sync</title>
</head>
<body>
  <div id="app">
    <child :name="name"></child>
    <button type="button" @click="changePropsInFather">在父组件中将props值改变为'props'</button>
  </div>
  <script src="https://unpkg.com/vue"></script>
  <script>
    // 定义一个子组件
    Vue.component('Child', {
      template: `<h1 @click="changePropsInChild">hello, {{name}}</h1>`,
      props: {
        name: String,
      },
      methods:{
        changePropsInChild(){
          this.name = 'I am from child'
        }
      },
    })
    // 实例化一个Vue对象
    const app = new Vue({
      el: '#app',
      data(){
        return {
          name: 'world'
        }
      },
      methods:{
        changePropsInFather(){
          this.name='I am from father'
        },
      },
    })
  </script>
</body>
</html>

这里写图片描述

没有.sync修饰符时,点击欢迎语,虽然子组件中确实将name属性修改了,但是在控制台中报错了,如图所示,大致意思就是在子组件中不要直接修改属性值。

.sync修饰符时

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>.sync</title>
</head>
<body>
  <div id="app">
    <child :name.sync="name"></child>
    <button type="button" @click="changePropsInFather">在父组件中将props值改变为'props'</button>
  </div>
  <script src="https://unpkg.com/vue"></script>
  <script>
    // 定义一个子组件
    Vue.component('Child', {
      template: `<h1 @click="changePropsInChild">hello, {{name}}</h1>`,
      props: {
        name: String,
      },
      methods:{
        changePropsInChild(){
          this.$emit('update:name', 'I am from child');
        }
      },
    })
    // 实例化一个Vue对象
    const app = new Vue({
      el: '#app',
      data(){
        return {
          name: 'world'
        }
      },
      methods:{
        changePropsInFather(){
          this.name='I am from father'
        },
      },
    })
  </script>
</body>
</html>
  • 代码copy到编辑器中保存为.html文件,用浏览器打开观察结果。

可以发现通过.sync修饰符可以很好地解决子组件中修改属性并传递给父组件。

关于.sync修饰符

Vue官网上对.sync也有解释,简言之,:name.sync就是:name="name" @update:name="name = $event"的缩写。
即上面代码中的

......
<child :name.sync="name"></child>
......

等价于

......
<child :name="name" @update:name="name = $event"></child>
......

猜你喜欢

转载自blog.csdn.net/xum222222/article/details/80267087