vuex笔记

Vue x

在开发中,我们会的应用程序需要处理各种各样的数据,这些数据需

要保存在我们应用程序中的某一个位置,对于这些数据的管理我们就

称之为是 状态管理

src/store/index.js

import { createStore } from "vuex"
const store=createStore({
state:()=>({
  counter:0
})
})
export default store

main.js

import store from './store'
createApp(App).use(store).mount('#app')

单一状态树

 用一个对象就包含了全部的应用层级的状态;

 采用的是SSOT,Single Source of Truth,也可以翻译成单一数据源;

单一状态树的优势:

 如果你的状态信息是保存到多个Store对象中的,那么之后的管理和维护等等都会变得特别困难;

 所以Vuex也使用了单一状态树来管理应用层级的全部状态;

 单一状态树能够让我们最直接的方式找到某个状态的片段;

 而且在之后的维护和调试过程中,也可以非常方便的管理和维护;

方案1

import { computed} from 'vue';
import { mapState,useStore } from 'vuex';

const {name,level}=mapState(["name","level"])
const store=useStore()
const cname=computed(name.bind({$store:store}))
const clevel=computed(level.bind({$store:store}))

方案2:

const store=useStore()
const {name,level}=toRefs(store.state)

getters

getters:{
  doubleCounter(state){
    return state.counter*2
  },
  totalage(state){
    return state.user.reduce((pre,item)=>{
      return pre+item.age
    },0)
  },
  message(state,getters){
    return `${state.name}${getters.totalage}`
  }
},

mapGetters的辅助函数

import {mapGetters}from 'vuex'
computed:{
  ...mapGetters(["doubleCounter","totalage","message"])
}

actions的基本使用

Action类似于mutation,不同在于:

 Action提交的是mutation,而不是直接变更状态;

 Action可以包含任意异步操作;

 async fetchhomeMusicAction(context){
    // fetch("http://123.207.32.32:8000/home/multidata").then(res=>{
    //   return res.json()
    // }).then(data=>{
    //   console.log(data)
    // })
    const res=await fetch("http://123.207.32.32:8000/home/multidata")
    const data=await res.json()
    context.commit("changebanners",data.data.banner.list)
    context.commit("changerecomder",data.data.recommend.list)
  }

 

分发

methods:{
  actionbtnclick(){
    this.$store.dispatch("incrementAction")
  }
}

可以携带参数

this.$store.dispatch("changnameAction","aaa")
 
posted @ 2023-03-07 23:28  guorunbin  阅读(17)  评论(0编辑  收藏  举报