1、父值不能在子组件修改,需要通过子组件事件返回给父组件
父组件
<template>
<div>
<test :value="value" @change="change"></test>
</div>
</template>
<script>
import test from '@/components/test.vue'
export default {
components: {
test
},
data() {
return {
value: '父组件的值'
};
},
methods: {
change (value) {
this.value = value
}
}
}
</script>
子组件
<template>
<div>
<div>{{ value }}</div>
<button @click="change">改变父组件的值</van-button>
</div>
</template>
<script>
export default {
props: {
value: {
type: String
}
},
methods: {
change () {
this.$emit('change', '子组件调用父组件的change方法修改的')
}
},
};
</script>
2、子组件可以修改父组件的值(双向绑定)
父组件
<template>
<div>
<test v-model="value"></test>
</div>
</template>
<script>
import test from '@/components/test.vue'
export default {
components: {
test
},
data() {
return {
value: '父组件的值'
};
}
}
</script>
子组件
<template>
<div>
<div>{{ value }}</div>
<button @click="change">改变父组件的值</van-button>
</div>
</template>
<script>
export default {
props: {
value: {
type: String
},
},
model: {
prop: 'value',
event: 'changes'
}
methods: {
change () {
this.$emit('changes', '在子组件中修改父组件的值')
}
},
};
</script>