javascript - 如何正确地将我的“方法”从组件转移到 vuex?我在哪里做错了?
问题描述
单击“添加”按钮时,应检查是否在输入中输入了某些文本,如果是,则应将某些对象与输入的文本一起添加到输入中,然后保存在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;
},
}
}
});
解决方案
推荐阅读
- c# - 如何检测在 C# WPF 的列表视图中单击了哪一行和哪一列
- javascript - 检测 Node.js 的 Net 模块中的“数据”事件收到的完整数据
- javascript - jquery onchange函数没有调用
- python - 将 BeautifulSoup 汤转换为 lxml 元素
- macos - macOS中如何通过进程找到线程id?
- ffmpeg - FFMpeg 复制直播流(限制为 60 秒文件)
- batch-file - 用于执行文件夹中所有脚本的 Windows 批处理脚本
- android - 我如何在 imageview 上设置 textview 并在水平 Recycler View 内的图像边界底部设置文本中心
- javascript - ThreeJS隐藏纹理
- r - 使用长和宽到长的混合来重塑数据