Vuex
组成部分 1.action 2.mutation 3. state 边外component
通过组件通过dispatch派发action 类型有两种写法
// 以载荷形式分发
this.$store.dispatch('cart/delete',id)
// 以对象形式分发 store.dispatch({ type: 'cart/delete', id})
dispatch 派发完毕后 action进行commit() 例如:
delete({commit,state},id){ let item=state.items.find(item=>item.id==id) commit('delete',item) }
然后就会调用mutation mutation修改原state
delete(state,item){ state.items.forEach((aa,index,arr) => { if(arr[index]==item){ state.items.splice(index,1) }else{ console.log(1) } });
也就是这样
import Vue from 'vue' import Vuex from 'vuex' Vue.use(Vuex) import cart from './modules/cart.js' let store=new Vuex.Store({ modules:{ cart } }) export default store //然后在根组件引入这个 store import Vue from 'vue' import App from './App.vue' import router from './router/index.js' import store from './store/index.js' Vue.config.productionTip = false new Vue({ store, router, render: h => h(App) }).$mount('#app')
整个完整的vux操作流程就是这样的