Basic knowledge of
The official documentation
By default, a V-Model on a component makes use of a prop named Value and an event named Input
But input controls like checkboxes, checkboxes, and so on May use value attributes for different purposes. The Model option can be used to avoid such conflicts
Bind v-Models to components
The default bindingvalue
和 input
- In the parent component
father.vue
To bind the V-model for the child component son.vue
<template>
<div>
<Son v-model="flag">
</Son>
</div>
</template>
<script>
// Import child components
import Son from './son.vue'
export default {
components: {
FollowUser
},
data(){
return {
flag:true}}}</script>
Copy the code
- The child components
son.vue
On,- Receives the value passed by the V-Model on the parent component via the value of the props
props: { value: { type: Boolean.required: true}}Copy the code
- Emit the input event of the parent component via $emit
this.$emit('input',!this.value) Copy the code
<template>
<van-icon
@click="onClick"
:color="value ? '#ffa500' : ''"
:name="value ? 'star' : 'star-o'"
/>
</template>
<script>
export default {
props: {
value: {
type: Boolean.// Receive the value from the parent component V-model, i.e. Flag
required: true}},methods: {
// Click the button
onClick() {
// Update the flag value of the parent component by triggering the default input event of the parent component
// Change the flag of the parent component to false
this.$emit('input',!this.value)
}
}
}
</script>
Copy the code
The customvalue
andThe event
The name of the
- The child components
son.vue
On,- Receives the value passed by the V-Model on the parent component via the value of the props
model: { prop: 'isCheck'.// Accept the value of the V-model event: 'changeStatus' // Pass values to v-Model by triggering the changeStatus event }, props: { // The incoming value of the V-model isCheck: { type: Boolean.required: true}}Copy the code
- Emit the input event of the parent component via $emit
this.$emit('changeStatus',!this.isCheck) Copy the code
<template>
<van-icon
@click="onClick"
:color="isCheck ? '#ffa500' : ''"
:name="isCheck ? 'star' : 'star-o'"
/>
</template>
<script>
export default {
model: {
prop: 'isCheck'.// Accept the value of the V-model
event: 'changeStatus' // Pass values to v-Model by triggering the changeStatus event
},
props: {
// The incoming value of the V-model
isCheck: {
type: Boolean.required: true}},methods: {
// Click the button
onClick() {
// Update the flag value of the parent component by triggering the default input event of the parent component
// Change the flag of the parent component to false
this.$emit('changeStatus',!this.isCheck)
}
}
}
</script>
Copy the code