【问题标题】:Vue: add an item to a listVue:将项目添加到列表中
【发布时间】:2021-06-18 09:00:21
【问题描述】:

我是学习 Vue Js 的初学者。我正在尝试将一个项目添加到列表中,但它不起作用。我的列表处于 store 的状态,添加新元素的功能在 mutation 中。 Please 是允许添加新元素的功能编码错误或错误在其他地方。

请帮帮我。

这是我的 Vuex 商店代码

import Vue from "vue";
import Vuex from "vuex";

Vue.use(Vuex);

export default new Vuex.Store({
  state: {
    produits: [
            {text: "ananas", checked: true},
            {text: "banane", checked: false},
            {text: "orange", checked: true},
    ],
    newProduit: ''
  },
  mutations: {
    addItem: function(ecrit) {

      ecrit= this.state.newProduit.trim();
      if(ecrit) {
        this.state.produits.push({
          text:ecrit,
          checked: false
        });
      }
    }
  },
  actions: {},
  modules: {},
});

有我的组件代码

<template>
  <div>
    <b-input-group class="mt-3">
      <b-form-input></b-form-input>
      <b-input-group-append>
        <b-button variant="info" v-on:click="ajoutElement">Ajouter</b-button>
      </b-input-group-append>
    </b-input-group>
  </div>
</template>

<script>
export default {
  computed: {
    ajoutElement: {
      get() {
         return this.$store.state.produits;
      },
      set(value) {
        this.$store.commit('addItem',value)
      }
    }     
  }
}
</script>

提前感谢您的帮助

【问题讨论】:

  • 你的行动在哪里?使用 vuex 只需确保添加所有必需的状态管理标准原则。

标签: vue.js vuex


【解决方案1】:

您应该为您从组件中执行的每个操作添加操作。

我添加了一个动作 addItemAction。你可以看到这个作为参考,理想情况下你应该有 action-> commits-> mutation

在大型应用程序中,您甚至可以创建单独的模块,每个模块应该具有执行操作->提交->突变的功能

组件

set(value) {
        this.$store.dispatch('addItemAction',value); // Dispatch action with name and params.
      }

立即更新 vuex 商店

export default new Vuex.Store({
state: {
produits: [
        {text: "ananas", checked: true},
        {text: "banane", checked: false},
        {text: "orange", checked: true},
],
newProduit: ''
},
mutations: {
addItem: function(ecrit) {

  ecrit= this.state.newProduit.trim();
  if(ecrit) {
    this.state.produits.push({
      text:ecrit,
      checked: false
    });
  }
}
 },


actions: {
  addItemAction: function(context, ecrit){
    context.commit('addItem', ecrit); // Commit from here.
  }
},
modules: {},
});

【讨论】:

  • 非常感谢您的反馈。我添加了操作,但是当我输入一个项目并按下提交按钮时,该项目没有添加到列表中
  • 我分享了方法和示例代码,您可以创建 stackblitz 或者您可以详细查看文档vuex.vuejs.org/guide/actions.html#dispatching-actions Dispatching action from components。
  • 好的,但是我需要一位导师,一位 Vue Js 专家,当我遇到困难和需要准确解释时,我可以向他推荐。请你愿意成为我在 Vue Js 中的导师。对我在 Vue Js 中的发展有很大帮助
  • 当然,我相信分享知识和学习经验。在这里联系我linkedin.com/in/abhinavkumar985
  • 提前致谢,我只是在 LinkedIn 上向您发送邀请(venceslas koukou 我的 LinkedIn 个人资料)。
猜你喜欢
  • 2018-07-15
  • 1970-01-01
  • 2019-01-22
  • 2019-03-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-12-24
  • 2021-07-19
相关资源
最近更新 更多