天天看點

vue修飾符.sync

father.vue
<template>
  <div class="father">
    {{father}}
    <child :child.sync="father"></child>
  </div>
</template>

<script>
import child from './child.vue'
export default {
  name: 'father',
  data(){
    return{

    father:'father'
    }
  },
  props: {
  },
  watch: {
    father(newValue,oldValue) {
      console.log("我變了");
    }
  },
  computed: {
    mother: function() {//注意不能用箭頭函數
      return this.father + " is my husband";
    }
  },
  components:{
    child
  }
}
</script>
           

child.vue

<template>
  <div class="child">
    {{child}}
    <button @click="pass">傳新值給爸爸和自己</button>
  </div>
</template>

<script>
export default {
  name: "child",
  data() {
    return {
    };
  },
  props: ["child"],
  methods: {
    pass() {
      this.$emit('update:child', 'malinshu')
    }
  }
};
</script>
           

效果

點選按鈕前

vue修飾符.sync

點選後

vue修飾符.sync

這樣父子元件的資料就同步了,child改變的時候,father元件的father變量也跟着變

繼續閱讀