入门Vue的.sync修饰符

236 阅读1分钟

何为.sync?

  • .sync修饰符是一个语法糖
  • 在Vue中,子父组件之间最常用的通信方式就是通过props
  • props值只能在父组件中更新,并传递给子组件。在子组件内部,不允许改变传递进来的props值,保证数据的单向流通
  • 但有时候,我们需要在子组件内部改变props属性并更新到父组件中,这时候就需要用到.sync修饰符

代码示例

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

没有.sync修饰符的代码:

<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>

.sync修饰符的代码:

<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>

总结

:name.sync就是:name="name" @update:name="name = $event"的缩写。