在 Vue.js 中,props 是单向数据流,它们从父组件传递给子组件并且子组件不能直接修改 props。如果想要修改 props 的值,可以通过以下几种方式解决:
Vue.component('child-component', {
props: ['propValue'],
data() {
return {
localValue: this.propValue
}
},
methods: {
updatePropValue() {
this.localValue = 'new value';
}
},
template: `
Prop Value: {{ propValue }}
Local Value: {{ localValue }}
`
});
Vue.component('child-component', {
props: ['propValue'],
computed: {
localValue: {
get() {
return this.propValue;
},
set(newValue) {
// 修改 props 的值
this.$emit('update:propValue', newValue);
}
}
},
template: `
Prop Value: {{ propValue }}
Local Value: {{ localValue }}
`
});
注意:这种方法需要在父组件中监听子组件的事件,并在父组件中修改 props 的值。
Vue.component('child-component', {
props: ['propValue'],
methods: {
updatePropValue() {
this.$emit('update:propValue', 'new value');
}
},
template: `
Prop Value: {{ propValue }}
`
});
在父组件中监听子组件的事件,并在事件处理程序中修改 props 的值。
这样就可以在子组件中触发事件来间接修改父组件传递的 props 值。
下一篇:避免在Vue模板中重复模式