這是一個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);
}
}
}