vuex实现todoList实例

这是一个vuex的项目用例;旨在分割管理项目中的data,以组件为单位,利用vuex提供的module属性,进行 项目store的加载管理;最大限度的把逻辑分离出去,让模版文件专一作模版,让 store专心作数据管理。

src/store/index.js

import Vue from 'vue'
import Vuex from 'vuex'
import TodoList from '../components/todoList/store';

Vue.use(Vuex)

export default new Vuex.Store({
  state: {

  },
  mutations: {

  },
  actions: {

  },
  modules: {
      todoList:  TodoList
  }
})

todoList/index.vue

<template>
  <div>
    <div>
      <input type="text" :placeholder="state.placeholder" v-model="state.inputValue">
      <button type="button" @click="handleAddClick">添加</button>
    </div>
    <ul>
      <li v-for="(item, index) in state.list" @click="handleDelClick(index)">{{ item }}</li>
    </ul>
  </div>
</template>

<script>
import { mapState, mapActions } from "vuex";
export default {
  // 获取store里面的值
  computed: mapState({
    state: state => state.todoList
  }),
  methods: {
    ...mapActions(["handleAdd", "handleDel"]),

    handleAddClick() {
      this.handleAdd();
    },
    
    handleDelClick(index) {
      this.handleDel(index);
    }
  }
};
</script>

<style>
</style>

todoList/store.js

export default {
    state: {
        placeholder: 'todo info',
        inputValue: '',
        list: []
    },

    // 计算state状态生成新的状态
    getters: {

    },

    // 这里修改状态
    mutations: {
        handleAdd(state) {
            state.list.push(state.inputValue);
            state.inputValue = "";
        },
        handleDel(state, index) {
            state.list.splice(index, 1);
        }
    },

    // 这里触发mutations方法
    actions: {
        //这里的context和我们使用的$store拥有相同的对象和方法
        handleAdd(context) {
            context.commit('handleAdd');
        },
        handleDel(context, index) {
            context.commit('handleDel', index);
        }
    }
}

posted @ 2019-03-08 18:26  ghost2019  阅读(1579)  评论(0编辑  收藏  举报