vuex 的使用

博客介绍了vuex使用规则,包括获取index文件定义的state,在项目跳外链时若vuex数据不能及时获取需缓存;getters类似全局computed,可用于组装后端数据;还提及更改state里的值。此外,说明了vuex实现热更替本质是使用webpack的热更替。

vuex使用规则

统一管理数据

1.获取index文件定义的state

vuex来存的数据什么时候还要结合缓存?
项目跳外链的话vuex的数据都会消失,如果vuex存的数据不能及时再次获取,那么它需要缓存起来,以便再次给他复值

定义变量的文件
const state ={
  tokenId:'111111'
}
需要引入的那个文件,mapState其实就是state的地址(也可以直接使用this.$store.state调用)
 import {mapState} from 'vuex';
 
定义一个计算属性,在该页面可以直接使用引入的变量tokenId
computed:{
         ...mapState([
          "tokenId"
        ])
},
    mounted(){
        setTimeout(()=>{
            console.log(this.tokenId)
        },1000)
2.getters

getters类似于全局的computed。后端给我们数据不是我们想要的,需要组装一下,这个时候调用
当然也可以直接在页面里使用computed,当时如果多个页面都用到,去维护多个computed不明智
写法如下

export default {
  tokenIDs:(state)=>{   
    return `${state.tokenId} ${state.count}`;
  }
}

使用

import { mapGetters, mapState } from 'vuex'
  computed: {
    ...mapState(['count']),
    ...mapGetters(['tokenIDs']),
    counts () {
      return this.$store.state.count
    }
  }
  <p>{{tokenIDs}}</p> 
3.更改state里的值
调用import {mapMutations,mapActions} from 'vuex'(也可以直接使用this.$store.state赋值调用,最好不要直接改,不然定义state的意见就变低了)
    methods:{
      ...mapMutations([  //同步的
          'TOKEN'
      ]),
      ...mapActions([  //异步调用
          'getTOKEN'
      ])
    }
    在想调用的地方用this.TOKEN(data)调用
    附:mutation.js:
    import {
          TOKEN
        } from './types.js'
        export default {
          [TOKEN](state,res){
            state.tokenId=res;
          }
        };
        actions.js:
        import * as types from './types'
        export default {
          getTOKEN:({
            commit
          },res)=>{
            commit(types.TOKEN,res)
          }
        }
        
        
        简单区分同步还是异步调用 一般直接修改state的数据的,用mutation,异步的数据接口请求可以用actions
        
        this.TOKEN(11) = this.$store.commit('TOKEN',111)
        this.getTOKEN(11) = this.$store.dispatch('TOKEN',111)
vuex怎么实现热更替

vuex实现热更替,本质其实使用webpack的热更替

     if (module.hot) { //
    module.hot.accept([
      './state/state',  // 这里是对应的模块地址
      './mutation',
      './actions',
      './getters'
    ], () => {
      const newState = require('./state/state').default  // 采用的export default 的形式
      const newMutations = require('./mutation').default
      const newActions = require('./actions').default
      const newGetters = require('./getters').default

      store.hotUpdate({ // 启动热更替
        state: newState,
        mutations: newMutations,
        getters: newGetters,
        actions: newActions
      })
    })
  }

转载于:https://www.cnblogs.com/liuhuanwen/p/9554931.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值