v-model实现原理
v-model双向绑定实际就是数据绑定+事件绑定的一个语法糖
<input type="text"
v-model="inputVal">
/* 等价于*/
<input type="text"
v-on:value="inputVal"
@input="inputVal=$event.target.value">
v-model 封装组件
我们可以利用v-model的实现原理对组件进行封装
//父组件
<AddCount v-model="count"></AddCount>
/*相当于*/
<AddCount v-bind:count="count" v-on:change="count=$event.target.count"></AddCount>
//子组件
<template>
<div>
<input type="text"
@input="handleChange"
v-model="inputVal">
<span>{{inputVal}}</span>
</div>
</template>
<script>
export default {
name: "AddCount",
model: {//修改v-model映射关系
value: "count",
event: "change"
},
props: {
count: {
type: String,
default: ""
}
},
data() {
return {
inputVal: undefined
};
},
created() {
this.inputVal = this.count;
},
methods: {
handleChange() {
this.$emit("change", this.inputVal);
}
}
};
</script>
<component > 动态组件
利用v-model语法糖封装组件并实现动态组件主要是为了统一渲染element组件和自定义组件
<template>
<div>
<component v-for="item in tabs"
:key="item.key"
v-model="item.data"
:is="item.component"//动态渲染的组件名称
v-bind="item.props || {}"></component>
</div>
</template>
<script>
import AddCount from "./addCount.vue";
export default {
components: { AddCount },
data() {
return {
tabs: [
{
key: "tab1",
data: undefined,
component: "ElInput"
},
{
key: "tab2",
data: undefined,
component: "ElSwitch"
},
{
key: "tab3",
data: undefined,
component: "ElInput"
},
{
key: "tab4",
data: undefined,
component: "AddCount"
}
]
};
},
};
</script>