ComponentA.vue
<template>
<div>
<span>ComponentA: {{ title }}</span>
<button @click="back">回调</button>
</div>
</template>
<script>
export default {
name: 'ComponentA',
props: {
title: String
},
methods: {
back () {
console.log('back')
this.title = '回调了'
this.$emit('titleChanged', '子向父组件传值')
}
}
}
</script>
<style scoped>
</style>
HelloWorld.vue
<template>
<component-a :title='title' @titleChanged="onTitleChanged"></component-a>
</div>
</template>
<script>
import ComponentA from '@/components/ComponentA'
export default {
name: 'test',
components: {
ComponentA
},
data () {
return {
title: '向ComponentA传值',
}
},
methods: {
onTitleChanged (e) {
console.log('ontitleChanged', e)
},
}
</script>
<style scoped>
</style>
点击ComponentA 中的按钮:回调,title值修改成功了,但是会抛出vue的一个警告:
[Vue warn]: Avoid mutating a prop directly since the value will be overwritten whenever the parent component re-renders. Instead, use a data or computed property based on the prop's value. Prop being mutated: "title"
found in
---> <ComponentA> at src/components/ComponentA.vue
<Test> at src/components/HelloWorld.vue
<App> at src/App.vue
<Root>
经过研究发现一种修改方式:sync修饰符
修改ComponentA中的back方法:
back () {
console.log('back')
// this.title = '回调了'
this.$emit('titleChanged', '子向父组件传值')
this.$emit('update:title', 'newTitle')
}
修改HelloWorld中的布局:
<component-a :title.sync='title' @titleChanged="onTitleChanged"></component-a>