npm install vuex --save
npm uninstall vuex
npm install --save vuex@3
import Vue from 'vue'import Vuex from 'vuex'// 挂载VuexVue.use(Vuex)// 创建Vuex对象const store = new Vuex.Store({state:{// 存放的键值对就是所要管理的状态// 以key:value为例key:'value',marketName:'富民xx'},mutations:{setKey(state,payload){state.key = payload}}})// vue2,要使用vuex3才能正常运行,对应vue3要使用vuex4export default store
// 挂载storeimport store from './store'/* eslint-disable no-new */new Vue({el: '#app',router,store: store, //tore:store 和 router一样,将我们创建的Vuex实例挂载到这个vue实例中components: { App },template: '<App/>'})
computed:{key(){return this.$store.state.key},},
computed:{key:{get(){return this.$store.state.key;},set(val){this.$store.commit('setKey',val);}},},
watch:{key(val){console.log('key变了:'+val);}},
(1) state
// 创建Vuex对象const store = new Vuex.Store({state:{// 存放的键值对就是所要管理的状态// 以key:value为例key:'value',marketName:'富民xx'},})
组件中通过 this.$store.state.xxx 读取状态
computed:{key(){return this.$store.state.key},},
mapState 辅助函数
import { mapState } from 'vuex'export default {// computed:mapState({// key: state=>state.key,// marketName: state=>state.marketName// })// computed:mapState([// 'key',// 'marketName'// ])computed:{...mapState({key: state=>state.key,marketName: state=>state.marketName})}}
(2) Mutation
vuex中
mutations:{setKey(state,payload){state.key = payload},setMarket(state,val){state.marketName = val}}
组件中
key:{get(){return this.$store.state.key;},set(val){this.$store.commit('setKey',val);}},marketName:{get(){return this.$store.state.marketName;},set(val){this.$store.commit('setMarket',val);}},
(3) Getter
state:{// 存放的键值对就是所要管理的状态// 以key:value为例key:'value',marketName:'富民xx',todos: [{ id: 1, text: '...', done: true },{ id: 2, text: '...', done: false }]},getters:{doneTodos(state){return state.todos.filter(todo=>!todo.done)}},
arr(){return this.$store.getters.doneTodos}
结果:

(4) actions
注册一个简单的 action
actions:{increment({commit},val){commit('setMarket',val);}}
通过 store.dispatch 方法触发:
this.$store.dispatch('increment','菜丁农贸xx');
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号