码迷,mamicode.com
首页 > 其他好文 > 详细

vue-cli2使用store存储全局变量

时间:2020-05-22 18:50:58      阅读:201      评论:0      收藏:0      [点我收藏+]

标签:text   tle   引入   ons   对象   temp   put   this   rom   

1.引入store

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

import store from ‘./store‘	//+++

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

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

import Vue from ‘vue‘;
import Vuex from ‘vuex‘;
Vue.use(Vuex);

const state = {//要设置的全局访问的state对象
    textData: "Data from index",
};

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

export default store;

全局变量写在state里。

2.修改变量

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

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

3.获取变量

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

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

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

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

vue-cli2使用store存储全局变量

标签:text   tle   引入   ons   对象   temp   put   this   rom   

原文地址:https://www.cnblogs.com/dxy9527/p/12938838.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!