需求:父子組件value的雙向綁定
- v-model可以拆分爲@input和:value
- v-model實現雙向綁定是@input的回調函數中,執行賦值給value的語法糖
- 子組件向父組件通訊,第一個參數爲input,其實是給父組件中子組件@input回調中傳入參數並且設置對應value
- 改變父組件中對應雙向綁定的值,即可實現雙向綁定
- 只能實現子組件最上級元素的value綁定,適用於父組件控制子組件顯示隱藏等
父組件:
<template>
<div id='testModel'>
<button class="parent" @click="change">父組件按鈕</button>
<testChild v-model="isShow" :text="text"</testChild>
<!-- 以下是demo解釋 -->
<input type="text" v-model="inputVlu">
<!-- v-model可以做以下拆分 -->
<input type="text" @input="ipt" :value="inputVlu">
<!-- @input是v-on:input的語法糖 -->
<input type="text" v-on:input="ipt" :value="inputVlu">
</div>
</template>
<script>
import testChild from './testChild';
export default {
name: "testModel",
components:{testChild},
data() {
return {
isShow:true,
text:'哈哈哈',
inputVlu:'inputVlu',
}
},
methods:{
change(){
this.isShow=!this.isShow;
}
}
}
</script>
<style lang="scss" type="text/scss" scoped>
#testModel {
}
</style>
子組件:
<template>
<div id='testChild' :value="value" @input="setInput">
<div class="box" v-show="value">{{text}}</div>
<button @click="hid">子組件隱藏按鈕</button>
</div>
</template>
<script>
export default {
name: "testChild",
data() {
return {}
},
props: {
value: {
type: Boolean,
redirect: true,
},
text:{
type: String,
default:'信息',
},
},
methods: {
setInput(value) {
this.$emit('input', value);
//向父組件傳遞數據,以input爲對應函數key
//父組件中v-on:ipnut中ipnut的回調接收這裏的value值
},
hid(){
this.$emit('input', !this.value);
},
},
}
</script>
<style lang="scss" type="text/scss" scoped>
#testChild {
.box {
width: 100px;
height: 100px;
background-color: pink;
}
}
</style>