Vuex
1.安装vuex
npm install -save vuex
2. 引入 创建store文件夹目录
创建 vuex 指挥公共目录 store【'state','actions','mutations','getters','index'】
3.store -》index.js (所有的store下的都引入进去进行声明 )
import Vue from 'vue'
import Vuex from 'vuex'
import state from './state'
import mutations from './mutations'
import actions from './actions'
import getters from './getters'
Vue.use(Vuex)
/* eslint-disable new-cap */
export default new Vuex.Store({
state,
mutations,
actions,
getters
})
4.在main.js
/* 入口JS */ import Vue from 'vue' import App from './components/App' import store from './store' import './base.css' /* eslint-disable no-new */ new Vue({ el: '#app', // components:{App}, // template:'<App/>' render: h => h(App), store })
5.在组件儿中使用
1.this.$store.dispath('addTodo');
2.import {mapActions} from 'vuex'
...mapActions('addTodo')
6.
state 对应的data存放数据对象 state.todos
mutations 操作变更state数据
[CLEAR_ALL_COMPLETED](state){
state.todos = state.todos.filter(todo => (!todo.complete))
}
getters 计算state 计算属性的方法都是i在这里
totalCount(state){ return state.todos.length }
actions 触发mutations中的方法 this.$store.dispatch('removeTodo')
/*
组件写 this.$store.dispath('') 调用这里的方法
接受组件通知触发 mutation调用间接状态的方法的对象
*/
import {ADD_TODO, DELETE_TODO, SELECT_ALL_TODOS, CLEAR_ALL_COMPLETED,RECEIVE_TODOS} from './mutation-types'
import storageUtil from '../utils/storageUtils.js'
export default {
addTodo ({commit}, todo) {
commit(ADD_TODO, {todo})
},
deleteTodo({commit},index){
commit(DELETE_TODO,{index})
},
selectAllTodos ({commit}, check) {
commit(SELECT_ALL_TODOS, {check})
},
clearALLCompleted({commit}){
commit(CLEAR_ALL_COMPLETED)
},
reqTodos({commit},todos){
setTimeout(()=>{
// 读取数据
const todos = storageUtil.readTodos()
// 提交数据
commit(RECEIVE_TODOS,todos)
},1000)
}
}