程序员鸡皮

文章 分类 评论
60 3 9

站点介绍

一名PHP全栈程序员的日常......

Vue3中Vuex状态管理库学习笔记(二)

abzzp 2024-07-10 321 0条评论 前端

首页 / 正文
本站是作为记录一名北漂程序员编程学习以及日常的博客,欢迎添加微信BmzhbjzhB咨询交流......

发布于2024-07-04

10.mapMutations的使用

  1. 在options-api中
<template>
  <div>
   <button @click="changeName">修改name</button>
   <h2>Store Name:{{ $store.state.name }}</h2>
   <button @click="changeLevel">修改level</button>
   <h2>Store Level:{{ $store.state.level }}</h2>
   <button @click="changeInfo({name:'张三',level:'1999'})">修改level和name</button>
  </div>
</template> 

<script>
  import { mapMutations } from "vuex";
  import {CHANGE_INFO } from "@/store/mutation_types"
  export default {
    computed:{

    },
    methods:{
      btnClick(){
        console.log("btnClick")
      },
      ...mapMutations(["changeName","changeLevel",CHANGE_INFO])
    }
  }
</script> 

<style scoped>

</style>
  1. composition-api中
<template>
  <div>
   <button @click="changeName">修改name</button>
   <h2>Store Name:{{ $store.state.name }}</h2>
   <button @click="changeLevel">修改level</button>
   <h2>Store Level:{{ $store.state.level }}</h2>
   <button @click="changeInfo({name:'张三',level:'1999'})">修改level和name</button>
  </div>
</template> 

<script setup>
  import { mapMutations,useStore } from 'vuex';
  import { CHANGE_INFO } from "@/store/mutation_types"

  const store = useStore();
  // 1.手动映射和绑定
  const mutations = mapMutations(["changeName","changeLevel",CHANGE_INFO])
  const newMutations = {}
  Object.keys(mutations).forEach(key => {
    newMutations[key] = mutations[key].bind({$store:store})
  }) 
  const { changeName,changeLevel,changeInfo } = newMutations
</script>

<style scoped>

</style>

mutation重要原则
1.一条重要的原则就是要记住mutation必须是同步函数

  • 这是因为devtool工具会记录mutation的日记
  • 每一条mutation被记录,devtools都需要捕捉到前一状态和后一状态的快照
  • 但是在mutation中执行异步操作,就无法追踪到数据的变化

11. Actions的基本使用

<template>
  <div>
    <h2>当前计数:{{ $store.state.counter }}</h2>
    <button @click="actionBtnClick">发起action</button>
    <h2>当前计数:{{ $store.state.name }}</h2>
    <button @click="actionchangeName">发起action修改name</button>
  </div>
</template> 

<script>
  export default {
    computed:{

    },
    methods:{
      actionBtnClick(){
        this.$store.dispatch("incrementAction")
      },
      actionchangeName(){
        this.$store.dispatch("changeNameAction","bbb")
      }
    }
  }
</script>
<script setup>
 
</script>

<style scoped>

</style>

mapActions的使用

componets-api和options-api的使用

<template>
  <div>
    <h2>当前计数:{{ $store.state.counter }}</h2>
    <button @click="incrementAction">发起action</button>
    <h2>当前计数:{{ $store.state.name }}</h2>
    <button @click="changeNameAction('bbbccc')">发起action修改name</button>
    <button @click="increment">increment按钮</button>
  </div>
</template> 

<!-- <script>
 import { mapActions } from 'vuex';
  export default {
    computed:{

    },
    methods:{
      ...mapActions(["incrementAction","changeNameAction"])
    }
  }
</script> -->
<script setup>
   import { useStore,mapActions } from 'vuex';
   const store = useStore();
   const actions =  mapActions(["incrementAction","changeNameAction"]);
   const newActions = {}
   Object.keys(actions).forEach(key => {
    newActions[key] = actions[key].bind({$store:store})
   })
   const {incrementAction,changeNameAction} = newActions;
  //  2.使用默认的做法
  //  import { useStore } from 'vuex';
  // const store = useStore();
  // function increment(){
  //   store.dispatch("incrementAction")
  // }
</script>

<style scoped>

</style>

actions发起网络请求

  1. store/index.js文件
import { createStore } from "vuex";
import { CHANGE_INFO } from "./mutation_types";
const store = createStore({
  state:() => ({
    counter:100,
    name:'why',
    level:10,
    users:[
      {id:111,name:'why',age:20},
      {id:112,name:'kobe',age:30},
      {id:113,name:'james',age:25},
    ],
    friends:[
      {id:111,name:'why',age:20},
      {id:112,name:'kobe',age:30},
      {id:113,name:'james',age:25},
    ],
    // // 服务器数据
    banners:[],
    recommends:[]
  }),
  getters:{
    doubleCounter(state){
      return state.counter * 2
    },
    totalAge(state){
      return state.users.reduce((preValue,item)=>{
        return preValue + item.age
      },0)
    },
    message(state){
      return `name:${state.name} level:${state.level}`
    },
    // 获取某一个frends,是可以返回函数的
    getFriendById(state){
      return (id) => {
        const friend = state.friends.find(item=>item.id == id)
        return friend;
      }
    }
  },
  mutations: {
    increment(state){
      state.counter++
    },
    changeName(state){
      state.name = "王小波"
    },
    changename(state,name){
      state.name = name
    },
    changeLevel(state){
      state.level++
    },
    // changeInfo(state,userInfo){
    //   state.name = userInfo.name;
    //   state.level = userInfo.level
    // } 
    [CHANGE_INFO](state,userInfo){
      state.name = userInfo.name;
      state.level = userInfo.level
    },
    changeBanners(state,banners){
       state.banners = banners
     },
     changeRecommends(state,recommends){
       state.recommends = recommends
     }
  },
  actions:{
    incrementAction(context){
      // console.log(context.commit) // 用于提交mutation
      // console.log(context.getters) // getters
      // console.log(context.state) // state
      context.commit("increment")
    },
    changeNameAction(context,payload){
      context.commit("changename",payload)
    },
     async fetchHomeMultidataAction(context){
    //   // 1.返回promise,给promise设置then
    //   // fetch("http://123.207.32.32:8000/home/multidata").then(res=>{
    //   //   return res.json().then(data=>{
    //   //     console.log(data)
    //   //   })
    //   // })
    //   // 2.promisel链式调用 
    //   // fetch("http://123.207.32.32:8000/home/multidata").then(res=>{
    //   //   return res.json()
    //   // }).then(data =>{
    //   //   console.log(data)
    //   // })

       // 3.await/async 
       const res = await fetch("http://123.207.32.32:8000/home/multidata")
         const data = await res.json();
         console.log(data);
         // 修改state数据
         context.commit("changeBanners",data.data.banner.list)
         context.commit("changeRecommends",data.data.recommend.list)
         return 'aaaa';
    //   // return new Promise(async (resolve,reject)=>{
    //   //   const res = await fetch("http://123.207.32.32:8000/home/multidata")
    //   //   const data = await res.json();
    //   //   console.log(data);
    //   //   // 修改state数据
    //   //   context.commit("changeBanners",data.data.banner.list)
    //   //   context.commit("changeRecommends",data.data.recommend.list)
    //   //   // reject()
    //   //   resolve("aaaa")
    //   // })

    // }
  }
})

export default store
  1. HomeCom.vue
<template>
  <div>
    <h2>Home Page</h2>
    <ul>
      <template v-for="item in $store.state.home.banners" :key="item.acm">
        <li>{{ item.title }}</li>
      </template>
    </ul>
  </div>
</template> 

<script setup>
   import { useStore } from 'vuex';
  //  进行vuex网络请求
  const store = useStore()
  store.dispatch("fetchHomeMultidataAction").then(res=>{
    console.log("home中的then被回调:",res)
  })
</script>

<style scoped>

</style>

module的基本使用

  1. store/index.js文件
import { createStore } from "vuex";
import { CHANGE_INFO } from "./mutation_types";
import homeModule from './modules/home'
const store = createStore({
  state:() => ({
    counter:100,
    name:'why',
    level:10,
    users:[
      {id:111,name:'why',age:20},
      {id:112,name:'kobe',age:30},
      {id:113,name:'james',age:25},
    ],
    friends:[
      {id:111,name:'why',age:20},
      {id:112,name:'kobe',age:30},
      {id:113,name:'james',age:25},
    ],
    // // 服务器数据
    // banners:[],
    // recommends:[]
  }),
  getters:{
    doubleCounter(state){
      return state.counter * 2
    },
    totalAge(state){
      return state.users.reduce((preValue,item)=>{
        return preValue + item.age
      },0)
    },
    message(state){
      return `name:${state.name} level:${state.level}`
    },
    // 获取某一个frends,是可以返回函数的
    getFriendById(state){
      return (id) => {
        const friend = state.friends.find(item=>item.id == id)
        return friend;
      }
    }
  },
  mutations: {
    increment(state){
      state.counter++
    },
    changeName(state){
      state.name = "王小波"
    },
    changename(state,name){
      state.name = name
    },
    changeLevel(state){
      state.level++
    },
    // changeInfo(state,userInfo){
    //   state.name = userInfo.name;
    //   state.level = userInfo.level
    // } 
    [CHANGE_INFO](state,userInfo){
      state.name = userInfo.name;
      state.level = userInfo.level
    },
    // changeBanners(state,banners){
    //   state.banners = banners
    // },
    // changeRecommends(state,recommends){
    //   state.recommends = recommends
    // }
  },
  actions:{
    incrementAction(context){
      // console.log(context.commit) // 用于提交mutation
      // console.log(context.getters) // getters
      // console.log(context.state) // state
      context.commit("increment")
    },
    changeNameAction(context,payload){
      context.commit("changename",payload)
    },
    // async fetchHomeMultidataAction(context){
    //   // 1.返回promise,给promise设置then
    //   // fetch("http://123.207.32.32:8000/home/multidata").then(res=>{
    //   //   return res.json().then(data=>{
    //   //     console.log(data)
    //   //   })
    //   // })
    //   // 2.promisel链式调用 
    //   // fetch("http://123.207.32.32:8000/home/multidata").then(res=>{
    //   //   return res.json()
    //   // }).then(data =>{
    //   //   console.log(data)
    //   // })

    //   // 3.await/async 
    //   const res = await fetch("http://123.207.32.32:8000/home/multidata")
    //     const data = await res.json();
    //     console.log(data);
    //     // 修改state数据
    //     context.commit("changeBanners",data.data.banner.list)
    //     context.commit("changeRecommends",data.data.recommend.list)
    //     return 'aaaa';
    //   // return new Promise(async (resolve,reject)=>{
    //   //   const res = await fetch("http://123.207.32.32:8000/home/multidata")
    //   //   const data = await res.json();
    //   //   console.log(data);
    //   //   // 修改state数据
    //   //   context.commit("changeBanners",data.data.banner.list)
    //   //   context.commit("changeRecommends",data.data.recommend.list)
    //   //   // reject()
    //   //   resolve("aaaa")
    //   // })

    // }
  },
  modules:{
    home:homeModule
  }
})

export default store
  1. modules/home.js
export default{
  state:()=>({
    // 服务器数据
    banners:[],
    recommends:[]
  }),
  mutations:{
    changeBanners(state,banners){
      state.banners = banners
    },
    changeRecommends(state,recommends){
      state.recommends = recommends
    }
  },
  actions:{
    async fetchHomeMultidataAction(context){
      // 1.返回promise,给promise设置then
      // fetch("http://123.207.32.32:8000/home/multidata").then(res=>{
      //   return res.json().then(data=>{
      //     console.log(data)
      //   })
      // })
      // 2.promisel链式调用 
      // fetch("http://123.207.32.32:8000/home/multidata").then(res=>{
      //   return res.json()
      // }).then(data =>{
      //   console.log(data)
      // })

      // 3.await/async 
      const res = await fetch("http://123.207.32.32:8000/home/multidata")
        const data = await res.json();
        console.log(data);
        // 修改state数据
        context.commit("changeBanners",data.data.banner.list)
        context.commit("changeRecommends",data.data.recommend.list)
        return 'aaaa';
      // return new Promise(async (resolve,reject)=>{
      //   const res = await fetch("http://123.207.32.32:8000/home/multidata")
      //   const data = await res.json();
      //   console.log(data);
      //   // 修改state数据
      //   context.commit("changeBanners",data.data.banner.list)
      //   context.commit("changeRecommends",data.data.recommend.list)
      //   // reject()
      //   resolve("aaaa")
      // })

    }
  }
}
  1. HomeCom.vue
<template>
  <div>
    <h2>Home Page</h2>
    <ul>
      <template v-for="item in $store.state.home.banners" :key="item.acm">
        <li>{{ item.title }}</li>
      </template>
    </ul>
  </div>
</template> 

<script setup>
   import { useStore } from 'vuex';
  //  进行vuex网络请求
  const store = useStore()
  store.dispatch("fetchHomeMultidataAction").then(res=>{
    console.log("home中的then被回调:",res)
  })
</script>

<style scoped>

</style>

Modules-默认模块化

Home.vue

<template>
  <div>
    <h2>Home Page</h2>
    <h2>Counter模块的counter:{{ $store.state.counter.count }}</h2>
    <h2>Counter模块的doubleCounter:{{ $store.getters.doubleCount }}</h2>
    <button @click="incrementCount">count模块+1</button>
  </div>
</template> 

<script setup>
   import { useStore } from 'vuex';
  //  进行vuex网络请求
  const store = useStore()
  function incrementCount(){
    store.dispatch("incrementCountAction")
  }
</script>

<style scoped>
 
</style>

store/index.js文件

const counter = {
  namespaced:true,
  state:() =>({
    count:99
  }),
  mutations:{
    incrementCount(state){
      state.count++
    }
  },
  getters:{
    doubleCount(state,getters,rootState){
      return state.count + rootState.rootCounter
    }
  },
  actions:{
    incrementCountAction(context){
      context.commit("incrementCount")
    }
  }
}

export default counter

修改模块子的值

HomeCom.vue

<template>
  <div>
    <h2>Home Page</h2>
    <h2>Counter模块的counter:{{ $store.state.counter.count }}</h2>
    <h2>Counter模块的doubleCounter:{{ $store.getters["counter/doubleCount"] }}</h2>
    <button @click="incrementCount">count模块+1</button>
  </div>
</template> 

<script setup>
   import { useStore } from 'vuex';
  //  进行vuex网络请求
  const store = useStore()
  function incrementCount(){
    store.dispatch("counter/incrementCountAction")
  }
  // module修改或派发根组件
  // 如果我们希望在action中修改root中的state,那么有如下方式
  // changeNameAction({commit,dispatch,state,rootState,getters,rootGetters}){
  //   commit("changeName","kobe");
  //   commit("changeNameRootName",null,{root:true});
  //   dispatch("changeRootNameAction",null,{root:true});
  // }
</script>

<style scoped>
 
</style>

感谢观看,我们下次见

评论(0)

最新评论

  • abzzp

    十天看一部剧,还可以吧[[呲牙]]

  • ab

    @梦不见的梦 行,谢谢提醒,我优化一下

  • 梦不见的梦

    网站的速度有待提升,每次打开都要转半天还进不来呢

  • abzzp

    @React实战爱彼迎项目(二) - 程序员鸡皮 哪里有问题了,报错了吗?[[微笑]]

  • abzzp

    @Teacher Du 那是怕你们毕不了业,我大学那会儿给小礼品[[发呆]]

  • Teacher Du

    我们大学那会,献血还给学分~

  • @ab 我想去学网安,比如网警,但分也贼高😕

  • ab

    @夜 加油,你一样也可以成为程序员的,需要学习资料可以V我

  • 佬发布的好多技术文章似乎我只能评论这篇,真正的程序员!!哇塞 我也想去献血,过两年就成年了可以去献血了

日历

2024年11月

     12
3456789
10111213141516
17181920212223
24252627282930

文章目录

推荐关键字: vue JavaScript React Golang 观后感 ES6 读后感

站点公告
本站是作为记录一名北漂程序员编程学习以及日常的博客,欢迎添加微信BmzhbjzhB咨询交流......
点击小铃铛关闭
配色方案