单击“添加”按钮时,应检查是否在输入中输入了一些文本,如果是,则应在其中添加一些对象。文本输入到输入中,然后保存在 localstorage 中。当您重新启动程序时,该对象应返回到页面。也可以通过单击删除按钮来删除对象。对于该组件,此代码有效。
这是它的工作方式。
现在我需要将所有内容转移到vuex。但是我做不到这一点。当我在控制台的输入中输入文本时,出现错误“ v-on处理程序中的错误:” TypeError:e.target未定义“。当我从输入中移除焦点时,在那里输入的文本将会消失。此外,我无法使用v-model,因为框架7不支持它。
现在如何工作
我在组件中的代码
<f7-block strong>
<f7-block-title>Some items</f7-block-title>
<f7-block v-for="(cat, n) in compCats">
<span>{{ cat }}</span>
<f7-button fill color="red" @click="removeCat(n)">Delete Cat</f7-button>
</f7-block>
<f7-list form>
<f7-list-input
:value="compNewCats"
@input="newCatOnInput"
type="text"
placeholder="Заметка"
></f7-list-input>
<f7-button fill color="blue" @click="addCat">Add some item</f7-button>
</f7-list>
</f7-block>
<script>
export default {
computed:{
compCats(){
return this.$store.state.cats;
},
compNewCats(){
return this.$store.state.newCat;
}
},
mounted() {
if (localStorage.getItem('cats')) {
try {
this.cats = JSON.parse(localStorage.getItem('cats'));
} catch(e) {
localStorage.removeItem('cats');
}
}
},
methods: {
addCat(e) {
this.$store.commit('addNewCat');
},
newCatOnInput(e){
this.$store.commit('newCatInput', e.target.value);
},
removeCat(n){
this.$store.comit('removeSomeCat');
}
}
}
</script>
我在VUEX中的代码
export default new Vuex.Store({
state: {
cats:[],
newCat: null
},
mutations: {
addNewCat(state) {
if (!this.newCat) {
return;
}
this.state.cats.push(this.state.newCat);
this.state.newCat = '';
this.saveCats();
},
removeSomeCat(x) {
this.state.cats.splice(x, 1);
this.saveCats();
},
saveCats(state) {
const parsed = JSON.stringify(this.state.cats);
localStorage.setItem('cats', parsed);
},
newCatInput(payload) {
this.newCat = payload;
},
}
}
});