试图理解 Vue.js 中的 "undefined" 警告
Trying to understand "undefined" warning in Vue.js
这出现在我的浏览器控制台中:
[Vue warn]: Error when evaluating expression "permissions.edit": TypeError: Cannot read property 'edit' of undefined (found in component: <heading>)
相关代码:
{{ permissions | json }}
<a class="button" v-on:click="toggleEditMode" v-if="permissions.edit">{{ editMode ? 'Save' : 'Edit' }}</a>
结果:
权限显然不是未定义的。这是怎么回事?更令人困惑的是,如果我将文字对象传递给组件 (:permissions="{edit: true}"
),警告就会消失,但是 {{ permissions | json }}
的 json 输出看起来完全一样。
因为permissions
不是Vuepath
对象。一旦你将它作为 prop 传递,它就会变成一个,你将能够像那样引用它。您能否提供组件的完整代码以供进一步解释?
正如您在 post 的评论中所讨论的那样,这是由于您在 created()
中进行了异步 API 调用以最初获取权限对象。
我建议你使用类似 https://github.com/vuejs/vue-async-data. It allows you to get data asynchronously (e.g. with vue-resource) and gives you a way to hide components content until loading the data has finished 的东西。
虽然您可以自己轻松模拟:
data: function () {
return { loaded: false, permissions: {} }
},
created() {
return this.$http(...).then(function (result) {
this.permissions = result.data.permissions // or however your data is
this.loaded = true
})
}
并在模板中,使用 v-if="loaded"
包装 div 来隐藏内容,直到实际加载权限。
这出现在我的浏览器控制台中:
[Vue warn]: Error when evaluating expression "permissions.edit": TypeError: Cannot read property 'edit' of undefined (found in component: <heading>)
相关代码:
{{ permissions | json }}
<a class="button" v-on:click="toggleEditMode" v-if="permissions.edit">{{ editMode ? 'Save' : 'Edit' }}</a>
结果:
权限显然不是未定义的。这是怎么回事?更令人困惑的是,如果我将文字对象传递给组件 (:permissions="{edit: true}"
),警告就会消失,但是 {{ permissions | json }}
的 json 输出看起来完全一样。
因为permissions
不是Vuepath
对象。一旦你将它作为 prop 传递,它就会变成一个,你将能够像那样引用它。您能否提供组件的完整代码以供进一步解释?
正如您在 post 的评论中所讨论的那样,这是由于您在 created()
中进行了异步 API 调用以最初获取权限对象。
我建议你使用类似 https://github.com/vuejs/vue-async-data. It allows you to get data asynchronously (e.g. with vue-resource) and gives you a way to hide components content until loading the data has finished 的东西。
虽然您可以自己轻松模拟:
data: function () {
return { loaded: false, permissions: {} }
},
created() {
return this.$http(...).then(function (result) {
this.permissions = result.data.permissions // or however your data is
this.loaded = true
})
}
并在模板中,使用 v-if="loaded"
包装 div 来隐藏内容,直到实际加载权限。