Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。现在大型项目基本上都需要使用vuex,所以专门写一遍如何配置与使用vuex供人探讨。
一、安装vuex
1、终端安装 npm install vuex --save
2、创建store文件夹,文件夹里新建index.js与modules文件夹(vuex模块化)
index.js代码如下:
import Vue from 'vue' import Vuex from 'vuex' //引入模块 import a from './modules/a' import b from './modules/b' import c from './modules/c export default new Vuex.Store({ state: { axiosCancel: [] }, mutations: {}, actions: {}, modules: { a, b, c } })
modules里面放置store模块
比如a模块里面代码(namespaced作用:为了解决不同模块命名冲突的问题,将不同模块的
namespaced:true,之后在不同页面中引入getter、actions、mutations时,需要加上所属的模块名)
const state = { basePath: 'homepage' } const mutations = { CHANGE_BASEPATH: (state, path) => { state.basePath = path } } const actions = { changeBasePath({ commit }, path) { commit('CHANGE_BASEPATH', path) } } export default { namespaced: true, state, mutations, actions }
3 main.js文件引入
代码如下:
import Vue from 'vue' import App from './App.vue' import router from './router' import store from '@/store' Vue.config.productionTip = false Vue.prototype.$echarts = echarts new Vue({ router, store, render: h => h(App) }).$mount('#app')
二、使用vuex
新建一个demo代码如下:
<template> <div class="">a模块调用mutation的值:{{ basePath }}</div> </template> <script> import { mapState } from 'vuex' export default { components: {}, data() { return { } }, computed: { ...mapState({ 'basePath': state => state.a.basePath }) }, watch: {}, created() { // 使用a模块的state console.log(this.$store.state.a) // 使用a模块的mutation(不推荐这样写,推荐写成对象的形式{path:'qqqq'},这样可以传多个参) this.$store.commit('a/CHANGE_BASEPATH', 'qqqq') // 使用a模块的action this.$store.dispatch('a/changeBasePath', 'bbbb') }, mounted() {}, methods: {} } </script> <style lang="scss" scoped> </style>
把state放在computed里这样state的值改变dom的值也改变