You need to enable JavaScript to run this app. Vue.js按属性排序单词报Cannot read property错误如何解决
优惠活动
大模型
产品
解决方案
定价
更多

Vue.js按属性排序单词报Cannot read property错误如何解决

问题原因

你代码里存在三处核心错误,直接导致了该报错:

  • props定义不符合Vue规范
    Vue的props选项是用于声明父组件传入的属性,你的写法把默认值直接写在了props的类型定义位置,导致组件实例上的this.wordsPriority实际为undefined,当排序逻辑尝试读取this.wordsPriority['Circle']时就触发了该报错。正确的props声明需要单独指定类型和默认值。
  • 方法内访问属性未加this前缀
    isActive方法里直接使用wordsActive,没有加this前缀,运行时会因找不到变量抛出错误。
  • 排序方法无返回值,且违规修改Vuex state
    sortWordsByPriority方法直接修改了绑定到Vuex state的this.words,不符合Vuex不可直接修改state的规范,同时该方法没有返回值,v-for无法拿到排序后的数组渲染。
修正后的完整代码
<script src="https://unpkg.com/vue@2"></script>
<script src="https://unpkg.com/vuex"></script>

<div id="app">
  Words sorted by priority: <br/>
  <pre>
    <words-list></words-list>
  </pre>
</div>

<script>
const store = new Vuex.Store({
    state: {
        words: ['Circle', 'Blue', 'Apple'],
    }
})

Vue.component('words-list', {
    template: `
        <ul>
            <li v-for="word in sortWordsByPriority(words)" 
                v-show="isActive(word)"
            >{{ word }}</li>
        </ul>
    `,
    // 正确的props声明写法
    props: {
        wordsPriority: {
            type: Object,
            default: () => ({
                Apple: 20,
                Blue: 10,
                Circle: 0,
            })
        },
        wordsActive: {
            type: Array,
            default: () => [
                'Apple',
                'Blue',
            ]
        }
    },
    computed: {
        words() {
            // 用computed关联vuex state,复制新数组避免修改原state
            return [...this.$store.state.words]
        }
    },
    methods: {
        isActive(word) {
            return this.wordsActive.includes(word);
        },
        sortWordsByPriority(words) {
            // 返回排序后的新数组,不修改原数组
            return [...words].sort((a, b) => this.wordsPriority[b] - this.wordsPriority[a]);
        },
    },
});

new Vue({
    store,
    el: "#app",
})
</script>

内容的提问来源于stack exchange,提问作者Andreas Hunter

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.15 03:54:07