.sync是vue中用於實現簡單的“雙向綁定”的語法糖,在平時的開發中是非常使用的。
vue的prop是單向下行綁定:父級的prop的更新會向下流動到子組件中,但是反過來不行。可是有些情況,我們需要對prop進行“雙向綁定”。這個時候,就可以用.sync來解決
.sync用法
<text-document :title.sync="doc.title"></text-document> 當子組件需要更新 title 的值時,它需要顯式地觸發一個更新事件: this.$emit('update:title', newValue)
這樣title的屬性在子組件內部更新,父組件也能感知的到,實現了“雙向綁定”。
.sync應運實例
<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>默認初始值是{{show}},所以是顯示的</p> <button @click.stop="closeDiv">關閉</button> </div>`, props:['show'], methods: { closeDiv() { this.$emit('update:show', false); //觸發 input 事件,並傳入新值 } } }) export default{ data(){ return{ valueChild:true, } }, methods:{ changeValue(){ this.valueChild = !this.valueChild } } } </script>
如果未觸發事件 this.$emit('update:show', false); 則外部感知不到子組件內部對show的改變,依然認為此事的值是true,導致彈框點擊打開一次之后,后面再不會打開。