定义:vue全局状态管理器 (在任意组件/页面都可以访问vuex的数据) (当数据更新的时候,引用vuex的组件视图会自动更新) export default new Vuex.Store({ state:{ 定义数据 Ps:user:{ math:1} $store.state 组件中访问} getters:{ 计算数据 Ps:gold(state){ return state.math +1 } $store.getter 组件中访问} mutations:{ 修改数据 类似组件中的methods mutation是修改state数据的唯一方法 mutations中的方法 按照国际惯例大写 $store.commit 组件中访问 Ps: ADD(state(原数据) ,data=100(要传入/更改的数据)){ state.math=data (更改state中的数据) } } actions:{ 异步操作 与后端接口放在actions中 $store.dispatch 组件中访问 PS:setScore(context, data) { context相当于组件中的$store,$store代表整个vuex,整个仓库 context.commit 调用mutations方法 context.dispatch 调用actions 方法 context.state 状态 context.getters 获取器 // 模拟异步操作 setTimeout(() => { // 调用mutations context.commit("ADD",data) },2000) } 引入模块 import 模块名 from 路径modules:{ 模块 模块名} }) vuex的映射方法 01导入: import { mapState,mapGetter ,mapActions,mapMutations} from "vuex" 02使用: 在computed去计算 computed:{ 映射带模块cart ..mapState({ goods:state=>state.cart.goods 不带模块 ...mapState([''userinfo'']) }) } 03在组件中使用 <p>{{goods}}</p> <p>{{userinfo}}</p> 其余如此(mapGetter ,mapActions,mapMutations) vuex中的state与getter映射为组件的data数据 vuex中的actions和mutations映射为组件methods方法