Vue中computed属性无法显示值:问题排查与修复咨询
问题原因分析
- 箭头函数导致
this指向异常:Vue的computed属性中使用箭头函数时,箭头函数不会绑定自身的this,而是继承外层作用域的this,这个this并非Vue组件实例,因此无法访问到实例上的name_属性,最终触发'name_' is not defined报错。 - 额外注意:代码中
components里注册的HelloWorld未导入,虽不是当前报错的直接原因,但会导致该组件无法正常使用,若需使用请补充导入语句。
修复方案
- 将computed中的箭头函数替换为普通函数,让
this正确指向Vue组件实例; - (可选)若需使用
HelloWorld组件,补充对应的导入语句。
修复后的完整代码:
<template> <div>computedProps:{{ calculated }}</div> </template> <script> // 若使用HelloWorld组件,需按实际文件路径导入,示例如下 // import HelloWorld from './components/HelloWorld.vue' export default { name: "App", components: { HelloWorld }, data() { const name_ = "ertz" const address_ = "aasf" const phone_ = "100 xx 50" return{ name_, address_, phone_ } }, computed: { // 替换为普通函数 calculated(){ return this.name_.length } } }; </script>
内容的提问来源于stack exchange,提问作者Amrmsmb
相关产品推荐
相关产品推荐

