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);
        }
    }
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM