Vuex 的项目实例4 添加事项

1、给添加事项按钮增加点击事件:

<a-button type="primary" @click="addItemToList">添加事项</a-button>

<script>
import { mapState } from 'vuex'
export default {
  methods: {
    // 添加事件 向列表中新增 item 项
    addItemToList() {
      if (this.inputValue.trim().length <= 0) {
        return this.$message.warning('文本框内容不能为空!')
      }
      this.$store.commit('addItem', this.inputValue)
    }
  }
}
</script>

2、打开 store/index.js 文件,添加变量 nextId 及 addItem :

state: {
    nextId: 5 // 下一个Id
},
mutations: {
    // 添加列表的 item 项
    addItem(state) {
      const obj = {
        id: state.nextId,
        info: state.inputValue.trim(),
        done: false
      }
      state.list.push(obj)
      state.nextId++
      state.inputValue = ''
    }
}

此时点击添加事件按钮,会把文件框中的内容,添加到 list 列表中。

 

原文地址:https://www.cnblogs.com/joe235/p/12738744.html