1. v-model
Problems to be solved
When using custom components, we sometimes need to use v-model
to 双向绑定
.
Two, the default use
In vue
, v-model
the value is equivalent to 默认
passing a name value 的 prop
and a name input 的方法
(note that this value
needs prop
to be declared in the custom component), as follows:
<template>
<div>
<p><a @click="click()">add</a></p>
<p>CTnum: {
{ num }}</p>
</div>
</template>
<script>
export default {
name: "CT",
props: {
value: {
type: Number,
default: 0,
},
},
data() {
return {
num: this.value,
};
},
mounted() {
},
methods: {
click() {
this.num++;
this.$emit("input", this.num);
},
},
};
</script>
<template>
<div>
<p>BT</p>
<CT v-model="num"></CT>
<p>BTnum: {
{ num }}</p>
</div>
</template>
<script>
import CT from "./CT.vue";
export default {
name: "BT",
components: {
CT },
data() {
return {
num: 0,
};
},
mounted() {
},
methods: {
},
};
</script>
3. Custom use
When used by default, 事件名input
and prop名value
are fixed, if you need to modify, you need to use model
options in subcomponents. as follows:
<template>
<div>
<p><a @click="click()">add</a></p>
<p>CTnum: {
{ num }}</p>
</div>
</template>
<script>
export default {
name: "CT",
model: {
prop: 'modelvalue',
event: 'change'
},
props: {
modelvalue: {
type: Number,
default: 0,
},
},
data() {
return {
num: this.modelvalue,
};
},
mounted() {
},
methods: {
click() {
this.num++;
this.$emit("change", this.num);
},
},
};
</script>
<template>
<div>
<p>BT</p>
<CT v-model="num"></CT>
<p>BTnum: {
{ num }}</p>
</div>
</template>
<script>
import CT from "./CT.vue";
export default {
name: "BT",
components: {
CT },
data() {
return {
num: 0,
};
},
mounted() {
},
methods: {
},
};
</script>