辉太郎看前端(vuex的使用)

前言

当面试官问你什么是vuex时,从以下几个方面回答

1.什么是vuex
2.vuex的核心
3.vuex的使用场景
4.vuex的运行机制

一丶什么是Vuex

Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。它采用集中式存储和管理程序的所有组件的数据

二丶Vuex的核心是什么

state 存储数据 在组件中的使用 this.$store.state.属性名

mutations 直接操作state中的数据,在组件中的this .$store.commit("方法名",参数)

actions 可以实现异步操作,在actions中操作mutations中的数据 在组件使用 this.$store.dispatch("方法名",参数)

getters getters类似于计算属性可以对state中数据进行逻辑计算 在组件中 this.$store.getters.方法名

modulesstate分模块

三丶vuex的运行机制

在组件中通过dispatch来调用actions中的方法,在actions中通过commit来调用mutations中的方法,在mutations中可以直接操作state中的数据,state的数据只要一发生改变立马响应到组件中。

  • 组件中
<template>
<div>
  <!--使用state中的数据-->
     {{$store.state.token}}
   <!--点击按钮触发事件-->
<button @click="btn">点击</button>
</div>
</template>

<script>
export default {
  methods:{
     btn(){
       //调用mutations中的方法
       this.$store.commit('set_token',"123456789")
       //调用actions中的方法
        this.$store.dispatch('to_token','abcdefg')
       }
   }
}
</script>

<style scoped>

</style>
  • Vuex中
import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
 state: {
  token:""
},
mutations: {
   set_token(state,val){
        state.token=val;
    }
},
actions: {
    to_token({commit},val){
       commit('set_token',val)
    }
},
modules: {
}
})

四丶使用场景

在大型的程序中如果多个组件中用到的数据我们可以存储到vuex,如果小型项目我们可以适当的使用vuex

五丶数据持久化

vuex中存放的数据,页面一经刷新就会丢失:

  • 存放在localStorage或者sessionStorage中,进入页面时判断是否丢失,丢失再去localStorage或者sessionStorage里面取。
  • app.vue根组件中判断是否丢失,在进行上面的操作。
    要用到vuex-persistedstate插件。
  1. 下载插件

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

      npm i vuex-persistedstate -S
  1. 配置在stroe.js中
import createPersistedState from 'vuex-persistedstate'
 export default new Vuex.Store({
     state,
     getters,
     mutations,
     actions,
      plugins: [createPersistedState({
       storage:window.sessionStorage
   })]
)}

六丶高级用法

模块化

数据量大时,将同类数据分模块存储,比如购物车数据,列表数据以及用户信息我们就可以分模块存储。

  • 在store.js中分模块存储
import vue from 'vue'
import Vuex from 'vuex'
Vue.use(vuex);

const state= ()=>{ token:''}
const actions = {}
const mutations = {}
const getters = {}
//user模块
let user = {
  namespaced: true, //一定要开始命名空间。
  state: { userid: 1234 },
  actions: {},
  mutations: {
    SET_USERID(state, val) {
      state.userid = val;
    }
  },
  getters: {}
}

//购物车数据的模块
let cart = {
  namespaced: true,
  state: { userid: 567 },
  actions: {},
  mutations: {},
  getters: {}
}


const store = new Vuex.Store({
  state,
  mutations,
  actions,
  getters,
  modules: {
    user,
    cart
  },
  plugins: [createPersistedState({
    storage: sessionStorage,
    key: "token"
  })]//会自动保存创建的状态。刷新还在
})

export default store
  • 在组件中调用
    注: 在普通调用时不用开启namespaced: true,在使用语法糖调用时,要开启命名空间。
获取user模块的`userid`
this.$store.state.user.userid
this.$store.commit("SET_USERID",12345)
语法糖
  • store.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 = {}


//user模块
let user = {
  namespaced: true, //一定要开始命名空间。
  state: { userid: 1234 },
  actions: {
  },
  mutations: {
    SET_USERID(state, val) {
      state.userid = val;
    }
  },
  getters: {

  }
}

//购物车数据的模块
let cart = {
  namespaced: true,
  state: { userid: 567 },
  actions: {

  },
  mutations: {
  },
  getters: {

  }
}


const store = new Vuex.Store({
  state,
  mutations,
  actions,
  getters,
  modules: {
    user,
    cart
  },
  //会自动保存创建的状态。刷新还在
  plugins: [createPersistedState({
    storage: sessionStorage,
    key: "token" //为存储到本地的名称
  })]
})

export default store
  • 组件中调用时
<template>
 <div id="">
   {{ token }}
   {{ token - x }}
 </div>
</template>

<script>
import { mapActions, mapGetters, mapMutations, mapState } from 'vuex'

import {createNamespacedHelpers} from 'vuex'

const {mapState:mapStateUser,mapActions:mapActionUser,mapMutations:mapMutaionuser} = createNamespacedHelpers('user')

const {mapState:mapStateCart,mapActions:mapActionCart,mapMutations:mapMutaionCart} = createNamespacedHelpers('cart')

export default {
 name: '',
 data() {
   return {}
 },
 computed: {
   ...mapState({
     token: 'token'
   }),
   ...mapGetters(['token-x']),
   ...mapSateUser(['userid']),
   ...mapStateCart({cartid:'userid'})
 },
 //生命周期 - 创建完成(访问当前this实例)
 created() {
   this.setToken('123456')
 },
 //生命周期 - 挂载完成(访问DOM元素)
 mounted() {},
 methods: {
   ...mapActions({
     setToken: 'setToken'
   }),
   ...mapMutations(['SET_TOKEN']),
   ...mapMutaionUser({
   setId:"setToken"
  })
 }
}
</script>
总结

初出茅庐,请各位大佬多多指教。👐

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值