store文件夹 vue_vue-cli2使用store存储全局变量

发布时间 2023-05-30 14:37:00作者: 回憶′亂人心

1.引入store

安装引入vuex,在main.js里面:

import store from './store' //store引入

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

在store文件夹下创建index.js入口文件,添加下面内容:

import Vue from 'vue';
import Vuex from 'vuex';

Vue.use(Vuex);

//要设置的全局访问的state对象
const state = {
    token: "",
    user:null    
};

const store = new Vuex.Store({
    state
});

export default store;

全局变量写在state里。

2.修改变量

在需要修改的地方使用this.$store.state.token=XXX进行修改:

watch: {
    dbData: function() {
        this.$store.state.token= this.dbData;
    }
}

3.获取变量

在需要获取的地方使用 XXX=this.$store.state.token进行获取:

data() {
    return {
        title: "11",
        textData: ""
    };
},

computed: {
    text() {
        return this.$store.state.textData; //需要监听的数据
    }
},

watch: {
    text(newVal, oldVal) {
        let that = this;
        //do something
        this.textData = newVal;
    },

},