如何在vue-cli中使用vuex

前言

众所周知,vuex 是一个专为 vue.js 应用程序开发的状态管理模式,在构建一个中大型单页应用中使用vuex可以帮助我们更好地在组件外部管理状态。而vue-cli是vue的官方脚手架,它能帮助我们方便的配置webpack。这样看来,有很大的可能我们需要同时使用vue-cli与vuex

如何在vue-cli中使用vuex

项目搭建及添加vuex
当我们使用vue-cli搭建一个vue项目的时候(假设项目名为learn-vuex),搭建完成后的文件目录是这样子的
这里写图片描述
首先使用npm install --save-dev vuex 把vuex添加到依赖,接下来就是如何在组件中使用vuex,大体上来说有以下两种形式。

通过 store 选项

如果vue-cli搭建成功,在src目录下会有一个main.js文件,main.js的主要作用是把项目中最顶层的app.vue组件挂载到DOM中,其他所有的组件都可以看做是app.vue的子组件。
在main.js中,做如下操作

import Vue from 'vue'
import App from './App'
import router from './router'
import Vuex from 'vuex'; 

Vue.config.productionTip = false

//注意下面的代码
Vue.use(Vuex);
const store = new Vuex.Store({
    state: {},
    getters: {},
    actions: {},
    mutations: {}
});
//注意router选项,此处的写法等同于store: store
new Vue({
  el: '#app',
  router,
  store,
  components: { App },
  template: '<App/>'
})

在组件中,就可以通过this.$store 来使用store实例
如果在项目中需要配置的vuex选项很多,我们则应该把vuex的相关代码分割到不同模块
在src下新建store文件夹,在文件夹中创建如下几个文件
这里写图片描述
我们可以随意设置文件名,但最好可以通过文件名就能判断出这个文件是用来干嘛的
index.js:整合各个模块,创建并导出vuex实例
rootState.js:配置vuex实例的state选项
getters.js:getter选项
mutations.js:mutations选项
actions.js:actions选项
在index.js中,我们需要

import Vue from 'vue';
import Vuex from 'vuex';
import state from './rootState.js';
import getters from './getters.js';
import mutations from './mutations.js';
import actions from './actions.js';

Vue.use(Vuex);
const store = new Vuex.Store({
    state,
    getters,
    actions,
    mutations
});

export default store;

剩下的四个文件配置都差不多一样,以rootState.js为例

const state = {
    count: 0,
    arr: [0,1,2,3,4,5]
}

export default state;

如此这般,在main.js中,我们需要编写的代码就减少了很多

import Vue from 'vue'
import App from './App'
import router from './router'
import store from './store/index'; 

Vue.config.productionTip = false

new Vue({
  el: '#app',
  router,
  store,
  components: { App },
  template: '<App/>'
})

将vuex实例挂载到vue原型链上

这是一种非主流的方式,主要是受axios启发,这里有一篇博客讲解如何在vue组件中使用axios,将axios挂载到vue原型链上是因为不能通过vue.use来使用axios
在这种方法中,我们需要

// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import router from './router'
import store from './store/index'; 

Vue.config.productionTip = false

//在vue中使用vuex必须先调用vue.use方法
Vue.use(Vuex);
//具体挂载到vue原型的哪个属性上,可以由我们自行决定
//遇到配置繁多的情况也可以进行分割
Vue.prototype.$store = new Vuex.Store({
    state: {},
    getters: {},
    actions: {},
    mutations: {}
});

//没有了store选项
new Vue({
  el: '#app',
  router,
  components: { App },
  template: '<App/>'
})

如此这般,还是可以通过this.$store 来使用vuex

猜你喜欢

转载自blog.csdn.net/wopelo/article/details/80284088