.sync是vue中用于實(shí)現(xiàn)簡單的“雙向綁定”的語法糖喇伯,在平時(shí)的開發(fā)中是非常使用的。
vue的prop是單向下行綁定:父級(jí)的prop的更新會(huì)向下流動(dòng)到子組件中颅眶,但是反過來不行审洞±苈可是有些情況,我們需要對(duì)prop進(jìn)行“雙向綁定”。這個(gè)時(shí)候,就可以用.sync來解決
.sync用法
<text-document :title.sync="doc.title"></text-document>
當(dāng)子組件需要更新 title 的值時(shí)锌蓄,它需要顯式地觸發(fā)一個(gè)更新事件:
this.$emit('update:title', newValue)
這樣title的屬性在子組件內(nèi)部更新,父組件也能感知的到仲器,實(shí)現(xiàn)了“雙向綁定”煤率。
.sync應(yīng)運(yùn)實(shí)例
<template>
<div class="details">
<myComponent :show.sync='valueChild' style="padding: 30px 20px 30px 5px;border:1px solid #ddd;margin-bottom: 10px;"></myComponent>
<button @click="changeValue">toggle</button>
</div>
</template>
<script>
import Vue from 'vue'
Vue.component('myComponent', {
template: <div v-if="show"> <p>默認(rèn)初始值是{{show}}仰冠,所以是顯示的</p> <button @click.stop="closeDiv">關(guān)閉</button> </div>
,
props:['show'],
methods: {
closeDiv() {
this.emit('update:show', false); 則外部感知不到子組件內(nèi)部對(duì)show的改變,依然認(rèn)為此事的值是true洋只,導(dǎo)致彈框點(diǎn)擊打開一次之后辆沦,后面再不會(huì)打開。