zhe*_*era 0 javascript vue.js vuejs2
vue中如何通过方法更新props值?所以我的 props 宽度默认值为 20
<div :style="{ width: width+ 'px'}">
Run Code Online (Sandbox Code Playgroud)
props: {
width: {
type: [String, Number],
default: '20px'
},
}
Run Code Online (Sandbox Code Playgroud)
然后它会将组件渲染为 width=20px。我可以使用 javascript 更改 props 值吗?例如它可能看起来像这样(?)
myEventHandler(e) {
if(window.innerWidth < 768 && this.width === '20')
this.width = '' // I want to revert the value to empty like it never used this props before. But I get vue warn that the prop being mutated
},
Run Code Online (Sandbox Code Playgroud)
任何帮助都会非常有帮助,谢谢!
小智 5
如 VueJs 文档中所述:https://v2.vuejs.org/v2/guide/components-props.html#One-Way-Data-Flow
这意味着您不应该尝试改变子组件内的 prop。如果这样做,Vue 将在控制台中警告您。
如果您确实需要改变道具,您可以尝试以下操作:在子组件中:
props: {
width: {
type: [String, Number],
default: '20px'
}
},
computed: {
computedWidth: {
get(){
return this.width
},
set(newValue) {
this.$emit('widthChanged', newValue)
}
}
}
Run Code Online (Sandbox Code Playgroud)
在父组件中:
<child-component
:width="width"
@widthChanged="someFunctionWhoMutateYourVar"
>
Run Code Online (Sandbox Code Playgroud)
这应该可以完成工作