VueJS TypeError:无法读取未定义的属性(读取"toLowerCase")



我可以在数组中进行筛选,并从该数组中删除项。当我尝试将项目添加到此数组列表时,问题就开始了。我得到以下错误:TypeError:无法读取未定义的属性(读取"toLowerCase"(。我不确定为什么会出现这个错误,因为当我使用add突变时,我甚至不希望使用我用于过滤器突变的getter。有人能向我解释这个错误意味着什么以及我如何修复它吗?

这是我的组件代码:

<template>
<div id="app">
<div>
<input type="text" v-model="query" placeholder="Search plants..." />
<div class="item fruit" v-for="fruit in filteredList" :key="fruit.msg">
<p>{{ fruit.msg }}</p> 
<button @click="deletePlants(index)">
Delete task
</button>
</div>
</div>
<div class="item error" v-if="query && !filteredList.length">
<p>No results found!</p>
</div>
<input v-model="fruits">
<button @click="addPlants">
New plant
</button>
</div>
</template>

<script>
import { mapMutations, mapGetters } from 'vuex'

export default {
name: 'SearchComponent',
props: {
msg: String
},
computed: {
...mapGetters([
'filteredList'
// ...
]),
query: {
set (value) {
this.setQuery(value);
},
get () {
return this.$store.state.query;
}
}

},
methods: {
...mapMutations([
'setQuery',
'addPlants',
'deletePlants',
'setPlants'
]),

}
};
</script>
<style>

这是我商店文件中的代码:

import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
strict: true,
state: {
query: '',
fruits: [
{ msg: 'Monstera'},
{ msg: 'Aloe vera'},
{ msg: 'Bonsai'},
{ msg: 'Cactus'},
{ msg: 'Bananenplant'},
{ msg: 'Ficus'},
{ msg: 'Calathea'},
]
},
mutations: {
setQuery(state, value ) {
state.query = value;
},
addPlants(state) {
state.fruits.push('Banana')
}, 
deletePlants (state, index){
state.fruits.splice(index, 1);
},
},
getters: {
filteredList (state) {
return state.fruits.filter((item) => {
return item.msg.toLowerCase().indexOf(state.query.toLowerCase()) !== -1
})
}
},
actions: {
},
modules: {
}
})

查看您的初始水果状态:

fruits: [
{ msg: 'Monstera'},
{ msg: 'Aloe vera'},
{ msg: 'Bonsai'},
{ msg: 'Cactus'},
{ msg: 'Bananenplant'},
{ msg: 'Ficus'},
{ msg: 'Calathea'},
]

然后看看你在这个数组中添加新水果的方式:

state.fruits.push('Banana')

你最终会得到这样的东西:

fruits: [
{ msg: 'Monstera'},
{ msg: 'Aloe vera'},
{ msg: 'Bonsai'},
{ msg: 'Cactus'},
{ msg: 'Bananenplant'},
{ msg: 'Ficus'},
{ msg: 'Calathea'},
'Banana',
]

要解决此问题,请将addPlants更新为state.fruits.push({ msg: 'Banana' })

最新更新