zoukankan      html  css  js  c++  java
  • vue-cli2使用store存储全局变量

    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;
        },
      },
    
  • 相关阅读:
    持续集成-禅道
    nohup.out 日志切分
    Flannel 介绍及使用场景
    【Unity游戏开发】初探Unity动画优化
    fastHttp服务端处理请求的过程
    PHPExcel导出文件代码实现
    PHPExcel 1.8
    CKfinder 安装与使用
    Ckeditor的配置
    Ckeditor的使用
  • 原文地址:https://www.cnblogs.com/dxy9527/p/12938838.html
Copyright © 2011-2022 走看看