Nag*_*Nag 2 javascript vue.js vuejs2
我正在构建一个使用Vuex的Vue 2 Webpack应用程序。我正在尝试通过观察从Vuex存储获取数据的计算属性来更新组件的本地状态。这是<script></script>
我的组件部分内部的样子:
export default {
name: 'MyComponent',
data() {
return {
// UI
modal: {
classes: {
'modal__show-modal': false,
},
tags: [],
},
};
},
computed: {
tagList() {
return this.$store.getters.tagList;
},
},
watch: {
tagList: (updatedList) => {
this.modal.tags = updatedList;
},
},
};
Run Code Online (Sandbox Code Playgroud)
如您所见,我有一个名为tagList的计算属性,该属性从商店中获取数据。我有一个监视tagList的观察器,以便每当商店的数据更改时,我都可以更新modal.tags
到新值。
根据Vue文档,我可以调用this.propertyName
和更新本地组件状态,但是当我调用时this.modal.tags = updatedList;
,出现以下错误:
[Vue warn]: Error in callback for watcher "tagList": "TypeError: Cannot set property 'tags' of undefined"
即使看起来与Vue.js文档中的内容没有什么不同,为什么也会发生此错误?
不要使用箭头功能。
更改自:
watch: {
tagList: (updatedList) => {
this.modal.tags = updatedList;
},
},
Run Code Online (Sandbox Code Playgroud)
至:
watch: {
tagList(updatedList) { // changed this line
this.modal.tags = updatedList;
},
},
Run Code Online (Sandbox Code Playgroud)
Vue文档几次提到了这一点:
不要 在options属性或回调函数上使用箭头功能,例如
created: () => console.log(this.a)
或vm.$watch('a', newValue => this.myMethod())
。由于箭头函数绑定到父上下文,this
因此不会像您期望的那样成为Vue实例,通常会导致诸如Run Code Online (Sandbox Code Playgroud)Uncaught TypeError: Cannot read property of undefined
要么
Run Code Online (Sandbox Code Playgroud)Uncaught TypeError: this.myMethod is not a function
基本上,这是一个上下文/范围的问题。使用箭头函数时,this
不会引用Vue实例,而是引用组件声明所在的封闭上下文(可能是window
)。
归档时间: |
|
查看次数: |
1689 次 |
最近记录: |