一、安裝vuex
npm install vuex --save
二、創建全局變量配置文件
cd src
mkdir store
然后創建store.js文件
三、倒入store.js文件
在main.js文件中添加 import Vuex from 'vuex' import store from './store/store'
new Vue({
el: '#app',
router,
store, // 將引用的文件添加到Vue項目中
components: { App },
template: '<App/>'
});
在store.js文件中添加 import Vue from 'vue' import Vuex from 'vuex' Vue.use(Vuex) export default new Vuex.Store({ state: { // 定義各種全局變量 }, mutations: { //定義各種方法,一般用於axios } })
引用變量
比如store.js文件中定義: state: { username: Cookie.get("username"), token: Cookie.get("token"), }, 那么在其他vue文件中引用如下: this.$store.state.token this.$store.state.username