1.使用v-model
父組件使用v-model屬性向子組件傳值
<cmbtpop v-model="show" :name="entity.name" ></cmbtpop>
子組件使用value屬性接受參數(當屬性名稱value被占用時可以使用model屬性修改接受v-model參數的屬性名稱,具體可參考model的api)
然后使用$emit方法更新父組件v-model參數
<div :show="newValue" @click="changeValue" >{{name}}</div> export default { name: 'cmbtpop', data() { return { newValue : this.value,//使用newValue 控制子組件 }; }, props: { value:{ type:Boolean, default: false } , name: String }, watch:{ value:function(){ this.newValue = this.value;//父組件的show值改變時重新控制子組件 } }, methods:{ changeValue(){ this.newValue = !this.newValue; this.$emit('input', this.newValue) // 父組件中的show會被更改成newValue值 } } }
2.使用同步后綴sync
在父組件的傳參屬后加入.sync標明該屬性同步
在子組件中使用$emit方法更新父組件同步屬性
<cmbtpop show.sync="show"></cmbtpop> //子組件 export default { props: { show: { type: Boolean, default: false } }, methods:{ changeValue(){
this.newValue = !this.newValue; this.$emit('update:show', this.newValue) // 父組件中的show會被更改成newValue值 }
} }
稱