首页 > 解决方案 > 如何正确地将我的“方法”从组件转移到 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;
        },
        }
    }
});

标签: javascriptvue.jsvuex

解决方案


推荐阅读