vuex

1.什么是vuex?

Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式,它由五部分组成:
分别是:state,actions,mutations,getters,modules
在这里插入图片描述

2.由5部分组成

  • state: 定义公共状态数据
  • actions:利用异步操作mutations来间接修改state中的状态
  • mutations: 唯一可以直接修改state中的状态
  • getters: 类似于vue组件中的计算属性,对state数据进行计算(会被缓存)
  • modules:模块化管理store(仓库),每个模块拥有自己的 state、mutation、action、getter

3.如何使用?

store—>index.js

import vue from 'vue'
import Vuex from 'vuex'
Vue.use(vuex);

const state= ()=>{ token:''}

const actions = {
  set_token({commit},val){
    commit("to_token",val)
 }
}
const mutations = {
  to_token(state,val){
   state.token=val;
 }
}
const getters = {}
let store = new Vuex.store({
 state,
 actions,
 mutations,
 getters
})

module.export=store;

组件中使用:

<template>
  <div>
    {{$store.state.token}}
  </div>
</template>

<script>
export default={
 name: 'Home',
  data() {
    return {
      tel: '',
       }
  },
  created(){
    //调用acionts中的方法
    this.$store.dispatch('set_token',12345);
    //调用mutations中的方法
    this.$store.commit('to_token',123456)
  }
}
<script>

4.高级用法-之 数据持久化

因为存储在vuex中的状态,刷新页面,会丢失。
为了解决刷新页面数据丢失,才有了数据持久化。

最简单的做法就是利用插件 vuex-persistedState

  • 安装

    npm install vuex-persistedstate --S
    

    -S 是–save的简写,意为:把插件安装到dependencies(生产环境依赖)中
    -D是–save-dev的简写,意为:把插件安装到devDependencies(开发环境依赖)中

  • 在store中

    import createPersistedState from 'vuex-persistedstate'
    const state = {
        user:{},
    }
    export default new Vuex.Store({
        state,
        getters,
        actions,
        mutations,
        
        plugins: [createPersistedState()]
        //会自动保存创建的状态,刷新还在。默认保存在localStorage中,key值默认为vuex
    	
    	plugins:[createPersistedState({
    		Storage:window.sessionStorage,
    		key:'data'
    	})]
    	//保存在sessionStorage中,key值为data
    });
    

5.高级用法-之 map辅助函数(语法糖)

  • 语法糖,辅助函数:mapState,mapActions,mapMutations,mapGetters
  • 辅助函数可以把vuex中的数据和方法映射到vue组件中。达到简化操作的目的
// 在vuex中
export default new Vuex.Store({
  state: {
    num: 1
  },
  mutations: {
    add(state){
    	num+= 1
    }
  },
  actions: {
  },
  getters:{
  },
  modules: {
  }
})


// 在组件中
import {mapState,mapGetters,mapActions,mapMutations} from 'vuex'

computed:{
	// 1. 直接引入
	...mapState(['num']), 
	
	//2.重命名
    ...mapState({
        app:"num", 
    }),


	...mapGetters()
}

methods:{
    // 1. 直接引入
	...mapMutations(['add']), 
	
	//2.重命名
    ...mapMutations({
        plus:"add", 
    }),

	
	...mapActions()
}



// 使用时

{{num}}  

<button @click='increament'></button>

methods:(){
	increament(){
		this.add()
	}
}

6.高级语法-值 模块化管理数据 (modules)

  • 状态树结构复杂的时候,可以用modules进行管理。

  • 多人协同开发,可以用modules,避免命名空间冲突。

//创建store,分模块定义

const  test1 ={
    namespaced:true, //开启命名空间(必须写*****)
    state:{name:'test1'},
    actions:{},
    mutations:{
    	changeName(state,arg){
            state.name=arg;
        },
    getters:{}
}

const test2 = {
    namespaced:true,
    state:{},
    actions:{},
    mutations:{},
    getters:{}
}

new Vuex.Store({
    state:{name:"root"},
    actions,
    mutations,
    getters 
    modules:{
        test1,
        test2
    }

})


//在组件中使用:

{{this.$store.state.name}}

{{this.$store.state.test1.name}}

{{this.$store.state.test2.name}}


<button @click='increament'></button>
methods:{
	increament(){
		this.$store.commit('test1/changeName','呵呵')
	}
}
  • modules单层模块下使用语法糖
import {mapState,mapGetters,mapActions,mapMutations,createNamespacedHelpers} from 'vuex'
const {mapState:mapStateUser,mapMutations:mapMutationUser} = createNamespacedHelpers('user')
// user 是store中的分类模块,map辅助函数名称不能相同。
// createNamespacedHelpers 创建一个新的辅助函数,基于某个命名空间上

computed:{
    ...mapState({
        a:"a", 
    }),
    
    ...mapStateUser({
        b:"b"
    }),
}

methods:{
    ...mapMutations({
        increament:"increament"
    }),
    
    ...mapMutationUser({
		getSync:'getSyncNum'
	})
}
  • modules多层模块下使用语法糖
let cart = {
  namespaced: true,
  state: {
    count: 100
  }
}

let user = {
  namespaced: true,
  state: {
    num: 1
  },
  mutations: {
    add(state,s) {
      state.num += s
    }
  },
  modules: {
    cart
  }
}

export default new Vuex.Store({
  state: {
    sum: 1
  },
  mutations: {
  },
  actions: {
  },
  modules: {
    user
  }
})

// 像这种层层嵌套分类
import { mapState, mapMutations, createNamespacedHelpers } from "vuex";
let { mapState: mapUser, mapMutations: mapUUUU } = createNamespacedHelpers(
  "user"
);
let { mapState: mapCart, mapMutations: mapCarts } = createNamespacedHelpers(
  "user/cart"
);

computed: {
   ...mapUser({
     app: "num",
   }),
   ...mapCart({
     sss: "count",
   }),
},


{{num}}  {{count}}



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值