vue添加使用全局變量


一、安裝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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM