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

本文介绍了如何在Vue项目中引入和配置Vuex来管理全局状态。首先在main.js中导入并创建store实例,然后在store/index.js中定义全局state。接着展示了如何通过`this.$store.state`来修改变量,以及在组件中使用计算属性和watch监听并获取state数据。通过这种方式,可以实现组件间的状态共享和更新。
摘要由CSDN通过智能技术生成

1.引入store

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

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

new Vue({

el: ‘#app‘,

router,

store,//+++

components: { App },

template: ‘‘

})

在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;

},

},

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值