Direct operation without writing theory
1. Parent component
<!-- 父组件 -->
<template>
<view>
<!-- 子组件 -->
<test v-model="parentValue" />
<!-- 父组件的值 -->
{
{
parentValue}}
</view>
</template>
<script>
//引用子组件
import test from '@/components/test/test'
export default {
//组册子组件
components: {
test
},
data() {
return {
//父组件的值
parentValue: 1
}
},
onLoad() {
},
methods: {
}
}
</script>
2. Subcomponents
<!-- 子组件 -->
<template>
<view>
<!-- 修改子组件的值 -->
<button @click="change(1)">
改变+1
</button>
<button @click="change(2)">
改变-1
</button>
</view>
</template>
<script>
export default {
name: "test",
data() {
return {
//子组件的值
num: 0
};
},
props: {
//父传子 也就是 v-model绑定的值
value: {
type: [String, Number],
default: 0
},
},
//
model: {
prop: 'value', //子组件接受父组件传来的 value名
event: 'changeValue', //子组件要更新父组件值需要注册的方法
},
created() {
// 初始化值
this.num = this.value
},
watch: {
// 监听 如果变化了就去重新赋值(这个没啥用 因为已经是双向绑定的 这里主要是要做一些处理事件)
value(newData) {
this.num = newData
}
},
methods: {
//子组件点击按钮 数量变化
change(type) {
if (type == 1) {
this.num += 1
} else {
this.num -= 1
}
this.changeValue(this.num)
},
//改变父组件绑定的值
changeValue(value) {
this.$emit('changeValue', value)
},
}
}
</script>
Note⚠️If
it is an event in the model under the mini program, you can only use input
model: {
prop: 'value', //子组件接受父组件传来的 value名
event: 'input', //子组件要更新父组件值需要注册的方法
},