Vue中.sync的用法


vue提供了.sync修飾符,說白了就是一種簡寫的方式,我們可以將其當作是一種語法糖,比如v-on: click可以簡寫為@click。

sync修飾符,與我們平常使用$emit實現父子組件通信沒有區別,只不過是寫法上方便一些。

日常開發時,我們總會遇到需要父子組件雙向綁定的問題,但是考慮到組件的可維護性,vue中是不允許子組件改變父組件傳的props值的。

那么同時,vue中也提供了一種解決方案.sync修飾符。在此之前,希望你已經知道了vue中是如何通過事件的方式實現子組件修改父組件的data的。

子組件使用$emit向父組件發送事件:

this.$emit('update:title', newTitle)

父組件監聽這個事件並更新一個本地的數據title:

<text-document
  :title="title"
  @update:title="val => title = val"
></text-document>

為了方便這種寫法,vue提供了.sync修飾符,說白了就是一種簡寫的方式,我們可以將其當作是一種語法糖,比如v-on: click可以簡寫為@click。

而上邊父組件的這種寫法,換成sync的方式就像下邊這樣:

<text-document
  :title.sync="title"
></text-document>

有沒有發現很清晰,而子組件中我們的寫法不變,其實這兩種寫法是等價的,只是一個語法糖而已,如果到這里你還不太明白。

下邊是個完整的demo,可以copy自己的項目中嘗試一下。相信你會恍然大悟。

Father.vue

<template>
  <div>
    <child :name.sync="name"></child>
    <button @click="al">點擊</button>
    <button @click="change">改變</button>
  </div>
</template>
 
<script>
import child from './Child'
export default {
  name: 'list',
  components: {
    child
  },
  data () {
    return {
      name: 'lyh'
    }
  },
  methods: {
    al() {
      alert(this.name)
    },
    change() {
      this.name = '123'
    }
  }
}
</script>

Child.vue

<template>
  <div>
    <input :value="name" @input="abc" type="text">
  </div>
</template>
<script>
  export default {
    props: {
      name: {
        type: String,
        required: true
      }
    },
    methods: {
      abc(e) {
        console.log(e.target.value)
        this.$emit('update:name', e.target.value)
      }
    }
  }
</script>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM