一基础

1.vuex基本概念

状态管理模式
响应式的数据状态
多组之间数据共享
不同视图改变同一个状态

2.vuex组成

state 数据仓库 (本质是json对象)
getter 获取数据(相当于 data和computed的区别)
mutation 修改数据 (commit一个mutation去修改数据,可以记录每个数据改变的历史,方比那监听,为同步操作 )
action 提交mutation 异步操作

3安装

npm install vuex
创建vuex实例:new VueX.store()
main.js中将vuex实例挂载到vue对象上

4.demo(vue3)

项目初始化
npm install -g @vue/cli
vue create vuex-demo
npm install vuex

代码(main.js)

import Vue from 'vue'
import App from './App.vue'
import Vuex from 'vuex'
Vue.config.productionTip = false
Vue.use(Vuex)
const store=new Vuex.Store({
  state:{
    count:0
  },
  mutations:{
    add(state,v){
        //  state.count++
        state.count=v
    }
  }
})
new Vue({
  store,
  render: h => h(App),
}).$mount('#app')

app.vue

<template>
  <div id="app">
    <!-- <h1>count:{{this.$store.state.count}}</h1> -->
    <h1>count:{{count}}</h1>
    <button @click="add">点我</button>
  </div>
</template>

<script>

export default {
  name: 'App',
  computed:{
    count(){
      return this.$store.state.count
    }
   
  }, 
  methods:{
      add(){
        const v=100
        // 调用store下面的mutationg中的add方法,俩个参数 2.参数值
        this.$store.commit('add',v)
      }
    }

}
</script>
<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

二vuex实操

1.登录操作关键代码片段

main.js路由守卫

router.beforeEach((to, from, next) => {
    if (store.state.userInfo || to.path === "/login") {
        next()
    } else {
        next({
            path: "/login"
        })
    }
})

login.vue

 setTimeout(() => {
               store.commit("login", {
                   account: that.form.account,
                   password: that.form.password
               });
               store.commit("setMemberInfo", {
                   userStatus: 0,
                   vipLevel: 0
               });
               that.$router.push("./");
           }, 500);

2.多组件共享会员信息

getters.js

export default {
    memberInfo(state) {
        switch (state.userStatus) {
            case 0:
                return "普通会员"
            case 1:
                return "vip会员"
            case 2:
                return `高级V${state.vipLevel}会员`
            default:
                return "普通会员"
        }
    }
}

index.vue(vuex解构代码片段)传入一个数组

import { mapGetters, mapState } from "vuex";
   computed: {
        ...mapState(["userStatus", "vipLevel"]),
        ...mapGetters(["memberInfo"])
    },

3.会员购买(调用mutations)

store/actions.js

export default {
//第一个参数是个对象 ,第二个是参数
    buyVip({ commit }, e) {
        return new Promise((resolve, reject) => {
            // mock api 交互
            setTimeout(() => {
                // 修改本地state
                commit("setMemberInfo", {
                    userStatus: e.userStatus,
                    vipLevel: e.vipLevel
                })
                resolve("购买成功")
            }, 1000)
        })
    }
}

userCenter.vue

store.dispatch("buyVip", e).then调用actions中的异步方法 dispatch传入两个参数(方法名字,参数值)
  buy(e) {
           store.dispatch("buyVip", e).then(res => {
               alert(res);
           });
       }

4.判断课程权限

goVideoList(e) {
          const res = this.checkPermission(e);
          if (res) {
              this.$router.push({
                  name: "course",
                  params: {
                      id: e.id
                  }
              });
          } else {
              alert("权限不足,无法观看");
          }
      },
      checkPermission(e) {
          const userStatus = this.$store.state.userStatus;
          const vipLevel = this.$store.state.vipLevel;
          if (userStatus >= e.userStatus) {
              if (vipLevel >= e.vipLevel) {
                  return true;
              } else {
                  return false;
              }
          } else {
              return false;
          }
      }

demo下载

https://gitee.com/cherry32/vuex-demo.git
作者不易,这个仓库设置了加密,如果您需要源码,请添加我的微信,给我一个硬币(一元钱)的打赏 我发给您~谢谢~


yujiao
23 声望6 粉丝

« 上一篇
深拷贝
下一篇 »
vue跨域post