如何解决:[Vue警告]:渲染错误:“ TypeError:无法读取未定义的属性...”

时间:2019-10-08 19:15:17

标签: javascript vue.js vuejs2

在Vue项目中,我试图返回一组工具中每个工具的URL。

上下文

这是ToolDetails.vue文件中的相关代码段:

<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?

1 个答案:

答案 0 :(得分:0)

此问题已解决。显然,此问题是由另一个文件ToolCard.vue引起的,该文件包含以下内容:

<div class="learn-cta">
  <router-link tag="a" :to="`tool/${data.tool_url}`">
    Learn More
  </router-link>
  <img src="@/assets/icons/arrow_blue.svg" />
</div>

引用tool_cards.json,在其中我需要添加一个tool_url行。这样就可以为每个工具链接正确生成URL,并且undefined错误消失了。