【发布时间】:2020-02-06 02:46:59
【问题描述】:
在一个 Vue 项目中,我试图为一组工具中的每个工具返回一个 URL。
背景
这是ToolDetails.vue 文件中的相关sn-p:
<script>
import { mapActions } from 'vuex';
import ToolFacts from '@/components/ToolFacts.vue';
import Matrix from '@/components/Matrix.vue';
import json from '../../models/content/tool_details.json';
export default {
name: 'tool-details',
components: {
ToolFacts,
Matrix,
},
data: () => ({
// tool: '',
}),
created() {
this.checkValidToolName();
// this.getToolName();
},
computed: {
tool() {
// eslint-disable-next-line
return Object.values(json).find(entity => entity.tool_url.toLowerCase() === this.$route.params.name.toLowerCase());
},
},
methods: {
getToolName() {
this.tool = json[this.$route.params.name];
// eslint-disable-next-line
return Object.values(json).for.find(entity => entity.tool_url.toLowerCase() === this.$route.params.name.toLowerCase());
},
getAssetPath(assetPath) {
// eslint-disable-next-line
return require(`../assets/${assetPath}`);
},
...mapActions(['SET_PRESELECTED_TOOL']),
compareTool() {
this.SET_PRESELECTED_TOOL(this.tool.name)
.then(this.$router.push('/compare'));
},
checkValidToolName() {
if (!this.tool) {
this.$router.push('/filter');
}
},
},
};
</script>
tool_details.json 的格式如下:
{
"Example Tool": {
"name": "Example Tool Name",
"tool_url": "example-tool-url",
...
},
...
}
问题
URL 在浏览器源代码中生成为undefined,控制台显示此错误:
vue.runtime.esm.js:619 [Vue warn]: Error in render: "TypeError: Cannot read property 'toLowerCase' of undefined"
found in
---> <ToolDetails> at src/views/ToolDetails.vue
<App> at src/App.vue
<Root>
vue.runtime.esm.js:1888 TypeError: Cannot read property 'toLowerCase' of undefined
at ToolDetails.vue:78
at Array.find (<anonymous>)
at VueComponent.tool (ToolDetails.vue:78)
at Watcher.get (vue.runtime.esm.js:4473)
at Watcher.evaluate (vue.runtime.esm.js:4578)
at VueComponent.computedGetter [as tool] (vue.runtime.esm.js:4830)
at Object.get (vue.runtime.esm.js:2072)
at Proxy.render (ToolDetails.vue?bf00:13)
at VueComponent.Vue._render (vue.runtime.esm.js:3542)
at VueComponent.updateComponent (vue.runtime.esm.js:4060)
当我放入调试器时,json 已定义,但未定义 entity。
我试过这样定义entity:
const entity = [];
还有这个:
const entity = {};
但我得到相同的控制台错误加上 ES Lint 错误:
'entity' is assigned a value but never used
如何解决该控制台错误以返回每个工具的正确 URL?
【问题讨论】:
-
您的
getToolName方法中似乎有错字。Object.values(json).for.find(enfor方法不存在。如果这不能解决它,请尝试查看您的tool_details对象中的内容,看看它是否错过了tool_url属性。 -
谢谢@EmielZuurbier。我删除了
for方法。感谢您的提醒。
标签: javascript vue.js vuejs2