Vue: 关于store的应用与方法

1. 建立项目基础公共状态

[src/store/common/common.js]

export default {
  namespaced: true, // 命名空间

  state: { // 数据存放
    clientId: 'c1', // 客户端ID
    clientSecret: 'vY9W55NuXM9hoDlx', // 客户端对称秘钥
    username: sessionStorage.getItem('username'), // 用户名
    userId: sessionStorage.getItem('userId'), // 用户ID
    accessToken: sessionStorage.getItem('accessToken'), // 访问Token
    refreshToken: sessionStorage.getItem('refreshToken') // 刷新Token
  },
  getters: { // 过滤器
  },
  mutations: { // 用于事件触发
    setState (state, payload) {
      state[payload.name] = payload.val
    }
  },
  actions: { // 用于触发事件, 执行异步操作触发mutations, 去更新state
  }
}

2. 把[Vuex模块]: common模块 --> 引入到根store的[Vuex]里

[src/store/index.js]

import Vue from 'vue'
import Vuex from 'vuex'
// 引入Vuex模块
import common from '@/store/common/common' // 引入
Vue.use(Vuex)

export default new Vuex.Store({
  state: {
  },
  mutations: {
  },
  actions: {
  },
  modules: {
    common //接取
  }
})

3. 从[Vuex模块]中取到自己需要的数据, 放在组件里

<template>
  <div class="vuexTest">
    vuex 模块化
    <button @click="getSetStateFun">改变数值</button>
  </div>
</template>

<script>
import { mapMutations } from 'vuex'

export default {
  name: 'VuexTest', // 组件名称
  methods: {
    ...mapMutations('common', {
      getSetState: 'setState'
    }),
    getSetStateFun () {
      this.getSetState({
        name: 'clientId',
        val: 123 // 此时的 clientId, 已经变成123
      })
      console.log(this.$store.state.common.clientId)
    }
  }
}
</script>

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值