vuex的简介
官方定义
Vuex是一个专门为Vue.js应用程序开的状态管理模式
它采用集中式存储管理应用的所有组件的状态
并以相应的规则保证以一种可预测的方式发生变化
应用场景
多个视图依赖同一状态
来自不同视图的行为需要改变同一个状态
Vuex的组成介绍
State --- 数据仓库
getter --- 用来获取数据的
Mutation --- 用来修改数据的
Action --- 用来提交mutation
安装Vuex
安装vuex包:npm install vuex
创建vuex实例:new Vuex.store()
main.js中将vuex实例挂载到vue对象上
实战vuex 实现count++ 基本demo
state中创建count字段
muntation中创建一个count++的mutation
button新增click事件触发mutation改变count
<template>
<div id="app">
<!-- <img alt="Vue logo" src="./assets/logo.png">
<HelloWorld msg="Welcome to Your Vue.js App"/> -->
<h1>count:{{count}}</h1>
<button @click="countIncrease">点我</button>
</div>
</template>
<script>
import HelloWorld from './components/HelloWorld.vue'
export default {
name: 'app',
components: {
HelloWorld
},
computed:{
count() {
return this.$store.state.count;
}
},
methods:{
countIncrease() {
const v = 100
this.$store.commit('countIncrease',v)
}
}
}
</script>
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:{
countIncrease(state,v){
state.count = v
}
}
})
new Vue({
store,
render: h => h(App),
}).$mount('#app')
案例讲解(业务目标)
制作一个需要账号登录的课程学习项目
不同的课程需要不同的会员等级,实现购买会员功能,课程分享
功能
通过state.userInfo控制用户登录路由限制
多组件共享state.userStatus和state.vipLeve状态
多组件修改state.userStatus和state.vipLevel

image.png

image.png

image.png

image.png
结构方法

image.png

image.png

image.png

image.png

image.png

image.png

image.png

image.png

image.png

image.png

image.png
网友评论