Instead, use a data or computed property based on the prop#39;s value. Vue JS(相反,使用基于道具值的数据或计算属性.Vue JS)
问题描述
好吧,我正在尝试在 Vue 中更改变量"的值,但是当我单击按钮时,它们会在控制台中抛出一条消息:
Well, I'm trying to change a value of "variable" in Vue, but when I click on the button they throw a message in console:
[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: "menuOpen"
我不知道如何解决这个问题...
I have no idea how to solve this problem...
我的文件.vue:
<template>
<button v-on:click="changeValue()">ALTERAR</button>
</template>
<script>
export default {
name: 'layout',
props: [ 'menuOpen' ],
methods: {
changeValue: function () {
this.menuOpen = !this.menuOpen
}
},
}
</script>
任何人都可以帮助我吗?谢谢
Any one can help me? Thanks
推荐答案
警告很清楚.在您的 changeValue
方法中,您正在更改属性 menuOpen
的值.这将改变组件内部的值,但是如果 parent 组件由于任何原因必须重新渲染,那么无论 inside 的值如何,组件都将被覆盖当前状态在组件之外.
The warning is pretty clear. In your changeValue
method you are changing the value of the property, menuOpen
. This will change the value internally to the component, but if the parent component has to re-render for any reason, then whatever the value is inside the component will be overwritten with the current state outside the component.
通常,您通过复制值供内部使用来处理此问题.
Typically you handle this by making a copy of the value for internal use.
export default {
name: 'layout',
props: [ 'menuOpen' ],
data(){
return {
isOpen: this.menuOpen
}
},
methods: {
changeValue: function () {
this.isOpen= !this.isOpen
}
},
}
如果您需要将值的更改传达回父级,那么您应该 $emit
更改.
If you need to communicate the change of the value back to the parent, then you should $emit
the change.
changeValue: function () {
this.isOpen= !this.isOpen
this.$emit('menu-open', this.isOpen)
}
这篇关于相反,使用基于道具值的数据或计算属性.Vue JS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:相反,使用基于道具值的数据或计算属性.Vue JS
基础教程推荐
- 在 JS 中获取客户端时区(不是 GMT 偏移量) 2022-01-01
- 动态更新多个选择框 2022-01-01
- 在for循环中使用setTimeout 2022-01-01
- 我什么时候应该在导入时使用方括号 2022-01-01
- 悬停时滑动输入并停留几秒钟 2022-01-01
- 角度Apollo设置WatchQuery结果为可用变量 2022-01-01
- 有没有办法使用OpenLayers更改OpenStreetMap中某些要素 2022-09-06
- Karma-Jasmine:如何正确监视 Modal? 2022-01-01
- 当用户滚动离开时如何暂停 youtube 嵌入 2022-01-01
- 响应更改 div 大小保持纵横比 2022-01-01