vuex 的 model mapActions persistedState的基础使用

9 篇文章 0 订阅
8 篇文章 0 订阅

vuex vue的状态管理器

//一般分为 state getter mutation action

创建model

创建一个login文件
// state
const state = {
  number: 10,
  
}

const getters = {
  number: (state) => state.number
}
// n为传递的参数
const mutations = {
  add(state, n) {
    state.number += n
  },
}
// action为触发mutation
const actions = {
  actionAcc: async ({ commit, getters }, n) => { //可传入getter state
    commit('add', n)
  },

}
//导出
export default {
  namespaced: true,
  state,
  mutations,
  getters,
  actions
}

//接收的index.js
// cnpm i -S vuex-persistedstate

import Vue from 'vue'
import Vuex from 'vuex'
import login from './login'
import persistedState from 'vuex-persistedstate' //保存刷新后的状态vuex
Vue.use(Vuex)

const store = new Vuex.Store({
  modules: {
    login
  },
  getters,
   plugins: [  //状态可以持续保存,添加即可
     persistedState({ storage: window.sessionStorage })
   ],
})

export default store


//vue 页面

import { mapState, mapMutations, mapGetters, mapActions } from "vuex";

//mapstate和mapgetter在computer使用,在后续方法里可以直接 this.num ,this.number
computed: {
    ...mapState("login", {
      nums: state => state.number
    }),
    ...mapGetters("login", ["number"]),
  },
  
//mapmutation和 mapActions 在methods使用
 // <div class="off" @click="cut()">挂断</div>
 
 methods:{
 // 声明mutation和actions
    mapMutation
    ...mapMutations(["login/add"]), 
    ...mapActions(
      ["login/actionAcc"]
    ),
    cut(){
        console.log(this.number,this.nums) //这两个结果是相同的
        this["login/add"](3);  // 调用mutation 3为传递的参数
        this["login/actionAcc"](4); //调用action 4为传递的参数
    }   
 }

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值