需求:父子组件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>