vuex基础入门

Vuex简介

vuex的安装和组成介绍
image.png

vuex简介

vuex是一个专门为vue.js应用程序开的状态管理模式
它采用集中式存储管理应用的所有组件的状态
并以相应的规则保证以一种可预测的方式发生变化

应用场景

移动端开发和工程化开发有丰富经验
uejs,node以及小程序有深入研究

多个视图依赖于同一状态
来自不同视图的行为需要改变同一个状态

vue安装和组成介绍

state
数据仓库

getter
用来获取数据的

mutation
用来修改数据的

action
用来提交mutation

安装vuex

安装vuex包,npm install vuex

扫描二维码关注公众号,回复: 6984172 查看本文章

创建vuex实例: new Vuex.store()

main.js中将vuex实例挂载到vue对象上

安装vuex实战

image.png

image.png

image.png

vue create vuex-demo

cd vuex-demo

code .

npm serve

yarn add vuex

main.js

import Vuex from 'vuex'

Vue.use(Vuex)

const store = new Vuex.store({
 state: {
  count: 0
 }
})

yarn serve

count++简介

state
中创建count字段

mutations
中创建一个count++ 的mutation

button
新增click事件触发mutation改变count

count++实战

const store = new Vuex.store({
 state: {
  count: 0
 },
 mutations: {
  countIncrease(state) {
   state.count++
  }
 // 第二种
 countIncrease(state, v) {
   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="countIncrease"></button>
 </div>
</template>

methods: {
 countIncrease() {
  const v=100;
  this.$store.commit('countIncrease', v)
 }
}

分析

账号登录
不同的课程需要不同的会员等级
普通会员
vip会员
高级会员

功能

通过state.userInfo控制用户登录路由限制
多组件共享state.userStatus和state.vipLevel状态
多组件修改state.userStatus和state.vipLevel

index.js

const store = new Vuex.Store({
 state,
 getters,
 mutations,
 actions
})

Vue.use(Vuex)

exprot default store;

store文件

action.js
getter.js
index.js
mutations.js
state.js

image.png

image.png

image.png

登录权限

store
index.js
state.js
mutations.js

// index.js

import Vue from 'vue'
import Vuex from 'vuex'
import state from './state'
import mutations from './mutations'

Vue.use(Vuex)

const store = new Vuex.Store({
 state,
 mutations
})

export default store

main.js

import Vue from "vue"
import App from "./App.vue"
import Vuex from "vuex"
import router from "./router"
import store from "./store"

Vue.config.productionTip = false

Vue.use(Vuex)

state.js

export default {
 userInfo: ""
}

main.js

Vue.prototype.$store = store
router.beforeEach((to, next) => {
 console.log(store.state, "store.state")
 if (store.state.userInfo || to.path('./login')) {
  next()
 } else {
  next({
    path: "/login"
  })
 }
})

state.js

export default {
 userInfo: "",
 userStatus: "",
 vipLevel: ""
}

若本号内容有做得不到位的地方(比如:涉及版权或其他问题),请及时联系我们进行整改即可,会在第一时间进行处理。


请点赞!因为你们的赞同/鼓励是我写作的最大动力!

欢迎关注达叔小生的简书!

这是一个有质量,有态度的博客

博客

猜你喜欢

转载自www.cnblogs.com/dashucoding/p/11324180.html
今日推荐