vue状态管理,配置vuex
Vue项目中经常会有对状态的控制操作,那么如何合理的封装使用呢?
main.js 引入store
//main.js import store from './store'; const app = new Vue({ router, store, ... })
创建store文件夹,新建index、rootState、getters、actions、mutations文件
├── src │ ├── main.js │ └── store │ |——index.js │ |——rootState.js │ |——getters.js │ |——actions.js │ |——mutations.js |——index.html
index.js文件
// 文件都会汇聚到这个地方来,也是创建store对象的地方,就像store的入口一样 //index.js import Vue from 'vue'; import Vuex from 'vuex'; import * as actions from './actions'; import * as mutations from './mutations'; import * as getters from './getters'; import state from './rootState'; Vue.use(Vuex) const store = new Vuex.Store({ state, getters, actions, mutations }) export default store;
rootState.js文件
//rootState.js const state = { userName : '' } export default state;
getters.js文件
//getters.js export const userName = state => state.userName;
mutations.js文件
//mutations.js export const setUserName = (state, payload) => { state.userName = payload.userName; }
actions.js文件
//actions.js export const setUserName = ({commit},userName) => { commit({ type: 'setUserName', userName }); };
使用 vuex,引入示例:
<template> <section class="wrap"> 引用vuex--userName的值为:{{userName}} </section> </template> <script> import {mapGetters} from 'vuex' export default { data () { return { } }, computed:{ ...mapGetters(['userName']) } } </script>