我可以過濾一個陣列,然后從這個陣列中洗掉專案。當我嘗試將專案添加到此陣列串列時,我的問題就開始了。我收到以下錯誤:TypeError: Cannot read properties of undefined (reading '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: {
}
})
uj5u.com熱心網友回復:
看看你最初的水果狀態:
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' })
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/507936.html
標籤:javascript Vue.js Vuejs2 Vue组件 Vuex
上一篇:i18n不允許嵌套占位符
