vue .sync 修饰符

2020-01-14  本文已影响0人  Fanny

.sync 修饰符作用: 让子组件可以更加优雅的修改父组件的data
单向数据流
所有的prop都是其父子prop之间形成一个单向下行绑定,:父级prop的更新会向下流到子组件中,但是反过来是不可以的(不可以在子组件中修改父组件传递的prop),这样会防止从子组件以外的改变父组件的状态,导致数据流向难以理解
prop使用
正常情况下,1.我们可以直接在template中使用prop的值 2. prop传递一个data的初始值,使其作为一个本地数据使用 3. 在计算属性中这个prop 作为一个初始值进行转换

1 . 通过.sync 使子组件修改父组件的data更加优雅

//父组件传递一个布尔值控制子组件的显示与隐藏,但是在子组件内部不可以直接修改这个prop,经常是通过事件的方式来修改, 使用 . sync 就是让这种方式变得简单
//paraent
 <div id="app">
      <h1>父组件---{{ showModal }}</h1>
      <myComponent :show.sync="showModal"></myComponent>
      <!-- 等同于下面这句 -->
      <!-- <myComponent :show="showModal" @update:show="val => showModal = val" ></myComponent> -->
 </div>
  data() {
    return {
      showModal: true
    };
  },

//child
 <div class="son">
    <h2 v-if="show">子组件----修改在子组件的msg</h2>
    <button @click="close">子组件--修改在子组件的msg</button>
 </div>
export default {
  props: ["show"],
  methods: {
    close() {
      this.$emit("update:show", !this.show);
    }
  }
};
20200114_134025.gif

2 . 在子组件通过触发事件事件修改父组件的data

//使用自定义事件,利用回调函数,使child中的值传递到paraent中从而修改父组件的值,改变状态
//paraent
<myComponent  :show="showModal" @transmsg="changemsg"></myComponent>
 data() {
    return {
      showModal: true
    };
  },
  methods: {
    changemsg(e){
      this.showModal = e
    },  
  }

//child
<div class="son">
    <h2 v-if="show">子组件----修改在子组件的msg</h2>
    <button @click="close">子组件--修改在子组件的msg</button>
</div>

 methods: {
    close() {
     this.$emit("transmsg",false)
    }
  }
自定义事件.gif
上一篇 下一篇

猜你喜欢

热点阅读