Vue - cli 使用 Vuex store 管理 变量,还有全局函数


npm install vuex -S

在目录下新建一个文件夹,store 

--------------store   //目录

-------modules      //放模块的

-------action.js     //暂时空白

-------index.js     //总的文件(主要的)

-------mutation-type.js   //还没用到

index.js

import Vue from "vue"
import Vuex from "vuex"
import increment from './mutation-types'
import style from './modules/style'
import globalObject from './modules/globalObject'
import urlObject from './modules/urlObject'

Vue.use(Vuex)
const state = {   //放变量名

}

export default new Vuex.Store({//放模块,state/mutations/actions,等
  modules:{
    style,
    globalObject,
    urlObject
  },
  state,
  mutations:{
    increment (value) {
    }
  }
})



index.js写完记得在目录下的main.js 添加 store模块

new Vue({
  el: '#app',
  router,
  store,   //在这里
  components: { App },
  template: '<App/>'
})

在模块里使用

import {  mapState,  mapActions} from 'vuex'

export default {
computed: {
    ...mapState([
      'style', 'userInfoObject'
    ]),
    ...mapActions([
      'isLoginOut'
    ])
  }
}
变量
在methods的话就这样用
that.$store.state.urlObject.host
在html直接就{{urlObject}}
方法:
使用的话直接在这个样子
that.isLoginOut()
如果要传参的话就这个样子
that.$store.dispatch("isLoginOut", res.data)

modules

globalObject.js

const globalObject = {
stste: {
}
actions: {
}
mutations: {

  }
}
export default globalObject

就这个样子啦

就是把这个文件加进去 store/index.js里面去

Vue的生命周期很重要,最好先去了解清楚



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值