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

1.什么是状态管理

在开发中,我们会的应用程序需要处理各种各样的数据,这些数据需要保存在我们应用程序的某个位置,对于这些数据的管理我们就称之为状态管理。

在之前我们如何管理自己的状态呢?

  • 在Vue开发中,我们使用组件化的开发方式;
  • 在组件中我们定义data或者在setup中返回使用的数据,这些数据我们称之为state;
  • 在模块template中我们可以使用这些数据,模块最终会被渲染成DOM,我们称之为View;
  • 在模块中我们会产生一些行为事件,处理这些行为事件时,有可能会修改state,这些行为我们称之为actions;

2.Vuex的状态管理

管理不断变化的state本身也是非常困难的:

  • 状态之间相互会存在依赖,一个状态的变化会引起另一个状态的变化,View页面也有可能引起状态的变化;
  • 当应用程序复杂时,state在什么时候,因为什么原因发生了变化,发生了怎么样的变化,会变得非常难以控制和追踪;
    因此,我们是否可以考虑将组件的内部状态抽离出来,以一个全局单例的方式来管理呢?
  • 在这种模式下,我们的组件树构成了一个巨大的 “试图View”;
  • 不管在树的那个位置,任何组件都能获取状态或者触发行为;
  • 通过定义和隔离状态管理中的各个概念,并通过强制性的规则来维护视图和状态间的独立性,我们的代码便会变得更加结构化和易于维护,跟踪;
    这就是Vuex背后的基本思想,它借鉴了Flux,Redux,Elm(纯函数语言,redux有借鉴它的思想);

当然,目前Vue官网也在推荐使用Pinia进行状态管理,我后续也会进行学习。

3.Vuex的状态管理

在这里插入图片描述

4.Vuex的安装

npm install vuex

5.Vuex的使用

在src目录下新建store目录,store目录下新建index.js,内容如下

import { createStore } from "vuex";

const store = createStore({
  state:() => ({
    counter:100
  })
})

export default store

在main.js中引用

import { createApp } from 'vue'
import App from './App.vue'
import store from './store'

createApp(App).use(store).mount('#app')

App.vue中使用

<template>
  <div class="app">
    <h2>App当前计数:{{ $store.state.counter }}</h2>
    <HomeCom></HomeCom> 
  </div>
</template>

<script setup>
  import HomeCom from './views/HomeCom.vue'
</script>

<style>
</style>

6.创建Store

每一个Vuex应用的核心就是store(仓库):

  • store本质上是一个容器,它包含着你的应用中大部分的状态(state);
    Vuex和单纯的全局对象有什么区别呢?
  1. Vuex的状态存储是响应式的
  • 当Vue组件从store中读取状态的时候,若store中的状态发生变化,那么相应的组件也会被更新;
  1. 你不能直接改变store中的状态
  • 改变store中的状态的唯一途径就是显示提交(commit)mutation;
  • 这样使得我们可以方便的跟踪每一个状态的变化,从而让我们能够通过一些工具帮助我们更好的管理应用的状态;

使用步骤:

  • 创建Store对象;
  • 在app中通过插件安装;

HomeCom.vue

<template>
  <div>
    <h2>Home当前计数:{{  $store.state.counter }}</h2>
    <button @click="increment">+1</button>
  </div>
</template>

<script setup>
  import { useStore } from 'vuex';
  const store = useStore()

  function increment(){
    // store.state.counter++
    store.commit("increment")
  }
</script>

<style scoped>

</style>

store/index.js

import { createStore } from "vuex";

const store = createStore({
  state:() => ({
    counter:100
  }),
  mutations:{
    increment(state){
      state.counter++
    }
  }
})

export default store

7.在computed中使用Vuex

options-api

<h2>Computed当前计数:{{ storeCounter }}</h2>
<script>
  export default{
    computed:{
      storeCounter(){
        return this.$store.state.counter
      }
    }
  }
</script>

Componsition-API

 <h2>Componsition-API中Computed当前计数:{{ counter }}</h2>
 const store = useStore()
  // const setupCounter = store.state.counter; // 不是响应式
  const { counter } = toRefs(store.state);

8.mapState函数

options-api中使用

    <!-- 普通使用 -->
    <div>name:{{ $store.state.name }}</div>
    <div>level:{{ $store.state.level }}</div>
    <!-- mapState数组方式 -->
    <div>name:{{ name }}</div>
    <div>level:{{ level }}</div>
    <!-- mapState对象方式 -->
    <div>name:{{ sName }}</div>
    <div>level:{{ sLevel }}</div>
<script>
  import { mapState } from 'vuex';
  export default {
    computed:{
      fullname(){
        return 'xxx'
      },
      ...mapState(["name","level"]),
      ...mapState({
        sName:state => state.name,
        sLevel:state => state.level
      })
    }
  }
</script>

Componsition-API

  <!-- Setup中  mapState对象方式 -->
    <!-- <div>name:{{ cName }}</div>
    <div>level:{{ cLevel }}</div> -->
    
    <!-- Setup中 使用useState -->
    <div>name:{{ name }}</div>
    <div>level:{{ level }}</div>
    
    <button @click="incrementLevel">修改level</button>
<script setup>
  // import { computed } from 'vue';
  // import { mapState,useStore } from 'vuex';
  import { useStore } from 'vuex';
// import useState from '../hooks/useState'
import { toRefs } from 'vue';

  // 1.一步步完成
  // const { name,level } = mapState(["name","level"])
  // const store = useStore()
  // const cName = computed(name.bind({ $store:store }))
  // const cLevel = computed(level.bind({ $store:store }))

  // 2. 使用useState
  // const { name,level } = useState(["name","level"])

  // 3.直接对store.state进行结构(推荐)
  const store = useStore()
  const { name,level } = toRefs(store.state)

  function incrementLevel(){
    store.state.level++
  }
</script>

hooks/useState.js

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

export default function useState(mapper){
  const store = useStore()
  const stateFnsObj = mapState(mapper)

  const newState = {}
  Object.keys(stateFnsObj).forEach(key=>{
    newState[key] = computed(stateFnsObj[key].bind({$store:store}))
  })

  return newState
}

9.getters的基本使用

某些属性可能需要经过变化后来使用,这个时候可以使用getters:

import { createStore } from "vuex";

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},
    ]
  }),
  mutations:{
    increment(state){
      state.counter++
    }
  },
  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}`
    }
  }
})

export default store

获取

<template>
  <div>
   <button @click="incrementLevel">修改level</button>
   <h2>doubleCounter:{{ $store.getters.doubleCounter }}</h2>
   <h2>usertotalAge:{{ $store.getters.totalAge }}</h2>
   <h2>message:{{ $store.getters.message }}</h2>
  </div>
</template>

<script>
  export default {
    
  }
</script>
<script setup>
  
</script>

<style scoped>

</style>

注意,getter是可以返回函数的

 // 获取某一个frends,是可以返回函数的
    getFriendById(state){
      return (id) => {
        const friend = state.friends.find(item=>item.id == id)
        return friend;
      }
    }

使用

<h2>friend-111:{{ $store.getters.getFriendById(111) }}</h2>

mapGetters的辅助函数

我们可以使用mapGetters的辅助函数
options api用法

<script>
  import { mapGetters } from 'vuex';
  export default {  
    computed:{
      // 数组语法
      // ...mapGetters(["doubleCounter","totalAge","message"]),
      // 对象语法
      ...mapGetters({
        doubleCounter:"doubleCounter",
        totalAge:"totalAge",
        message:"message"}),
      ...mapGetters(["getFriendById"])
    }
  }
</script>

**Composition-API中使用mapGetters **

<script setup>
   import { toRefs } from 'vue';
  //  computed
  import { useStore } from 'vuex';
  // mapGetters
  const store = useStore();

// 方式一
// const { message:messageFn } = mapGetters(["message"])
// const message = computed(messageFn.bind({ $store:store }))
// 方式二
const { message } = toRefs(store.getters)
function changeAge(){
  store.state.name = "coder why"
}
// 3.针对某一个getters属性使用computed
const message = computed(()=> store.getters.message)
function changeAge(){
  store.state.name = "coder why"
}
</script>

10. Mutation基本使用

更改Vuex的store中的状态的唯一方法是提交mutation:

mutations:{
	increment(state){
		state.counter++
	},
	decrement(state){
	   state.counter--
	 }
}

使用示例
store/index.js

import { createStore } from "vuex";

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},
    ]
  }),
  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 = "王小波"
    },
    changeLevel(state){
      state.level++
    },
    changeInfo(state,userInfo){
      state.name = userInfo.name;
      state.level = userInfo.level
    }
  },
})

export default store
<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">修改level和name</button>
  </div>
</template>

<script>
  export default {
    methods:{
      changeName(){
        console.log("changeName")
        // // 不符合规范
        // this.$store.state.name = "李银河"
        this.$store.commit("changeName")
      },
      changeLevel(){
        this.$store.commit("changeLevel")
      },
      changeInfo(){
        this.$store.commit("changeInfo",{name:'张三',level:'100'});
      }
    }
  }
</script>

<style scoped>

</style> 

Mutation常量类型
1.定义常量 store/mutation-type.js

export const CHANGE_INFO = "CHANGE_INFO"

2.定义mutation
引入 store/index.js

import { CHANGE_INFO } from "./mutation_types";
[CHANGE_INFO](state,userInfo){
      state.name = userInfo.name;
      state.level = userInfo.level
   }

3.提交mutation
引入 HomeCom.vue

import {CHANGE_INFO } from "@/store/mutation_types"
changeInfo(){
        this.$store.commit(CHANGE_INFO,{name:'张三',level:'100'});
      }

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>

感谢观看,我们下次见

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/424855.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

02、MongoDB -- MongoDB 的安全配置(创建用户、设置用户权限、启动安全控制、操作数据库命令演示、mongodb 的帮助系统介绍)

目录 MongoDB 的安全配置演示前准备&#xff1a;启动 mongodb 服务器 和 客户端 &#xff1a;1、启动单机模式的 mongodb 服务器2、启动 mongodb 的客户端 MongoDB 的安全配置启动演示用到的 mongodb 服务器 和 客户端启动单机模式的 mongodb 服务器&#xff1a;启动 mongodb 的…

光学遥感卫星分辨率的奥秘 !!

文章目录 前言 1、光学遥感卫星分辨率的多维视角 &#xff08;1&#xff09;空间分辨率 &#xff08;2&#xff09;光谱分辨率 &#xff08;3&#xff09;辐射分辨率 &#xff08;4&#xff09;时间分辨率 2、光学遥感分辨率的重要性 3、遥感分辨率的挑战与进步 4、未来展望 总…

《Spring Security 简易速速上手小册》第7章 REST API 与微服务安全(2024 最新版)

文章目录 7.1 保护 REST API7.1.1 基础知识详解7.1.2 重点案例&#xff1a;使用 JWT 进行身份验证和授权案例 Demo 7.1.3 拓展案例 1&#xff1a;API 密钥认证案例 Demo测试API密钥认证 7.1.4 拓展案例 2&#xff1a;使用 OAuth2 保护 API案例 Demo测试 OAuth2 保护的 API 7.2 …

【2024】利用python爬取csdn的博客用于迁移到hexo,hugo,wordpress...

前言 博主根据前两篇博客进行改进和升级 利用python爬取本站的所有博客链接-CSDN博客文章浏览阅读955次&#xff0c;点赞6次&#xff0c;收藏19次。定义一个json配置文件方便管理现在文件只有用户名称,后续可加配置读取用户名称&#xff0c;并且将其拼接成csdn个人博客链接ty…

OpenChat:性能高达105.7%,第一个超越ChatGPT的开源模型?

OpenChat&#xff1a;性能高达105.7%&#xff0c;第一个超越ChatGPT的开源模型&#xff1f; 前几天开源模型第一还是是Vicuna-33B、WizardLM&#xff0c;这不又换人了。对于开源模型的风起云涌&#xff0c;大家见怪不怪&#xff0c;不断更新的LLM榜单似乎也没那么吸引人了。 …

数学建模【因子分析】

一、因子分析简介 因子分析由斯皮尔曼在1904年首次提出&#xff0c;其在某种程度上可以被看成是主成分分析的推广和扩展。 因子分析法通过研究变量间的相关系数矩阵&#xff0c;把这些变量间错综复杂的关系归结成少数几个综合因子&#xff0c;由于归结出的因子个数少于原始变…

C/C++工程师面试题(数据库篇)

索引的优缺点 索引是一种支持快速查找特定行的数据结构&#xff0c;如果没有索引&#xff0c;就需要遍历整个表进行查找。用于提高数据检索的速度和效率。 好处&#xff1a; 提高检索速度&#xff1a; 索引可以加快数据的检索速度&#xff0c;因为它们允许数据库系统直接定位到…

Mysql学习之MVCC解决读写问题

多版本并发控制 什么是MVCC MVCC &#xff08;Multiversion Concurrency Control&#xff09;多版本并发控制。顾名思义&#xff0c;MVCC是通过数据行的多个版本管理来实现数据库的并发控制。这项技术使得在InnoDB的事务隔离级别下执行一致性读操作有了保证。换言之&#xff0…

【Tomcat】The CATALINA_HOME environment variable is not defined correctly

文章目录 一、问题二、解决办法三、优化 一、问题 运行绿色版Tomcat时&#xff0c;单击apache-tomcat-9.0.27\bin\startup.bat时窗口一闪而过。 检查JAVA_HOME环境变量&#xff0c;可以发现并没有问题。 为了检查错误&#xff0c;将startup.bat程序使用文本编辑器打开&#x…

Debezium发布历史163

原文地址&#xff1a; https://debezium.io/blog/2023/09/23/flink-spark-online-learning/ 欢迎关注留言&#xff0c;我是收集整理小能手&#xff0c;工具翻译&#xff0c;仅供参考&#xff0c;笔芯笔芯. Online machine learning with the data streams from the database …

C++_程序流程结构_选择结构_switch

作用 执行多条件分支语句 语法 if和switch区别 switch 缺点&#xff0c;判断的时候只能是整形或者字符型&#xff0c;不可以是一个区间switch 优点&#xff0c;结构清晰&#xff0c;执行效率高

go 命令行框架cobra

go 命令行框架cobra go 拉取依赖包go get github.com/spf13/cobra 认识spf13/cobra-cli. cobra 命令行框架在golang中的地位也算得上是大明星级别。像k8s,docker都有使用这个框架构建自己命令行这块的功能. 最最最简单的开始----使用命令行工具cobra-cli来初始化你的demo c…

四种策略改进的麻雀算法!效果起飞!你确定不来看看吗?

声明&#xff1a;文章是从本人公众号中复制而来&#xff0c;因此&#xff0c;想最新最快了解各类智能优化算法及其改进的朋友&#xff0c;可关注我的公众号&#xff1a;强盛机器学习&#xff0c;不定期会有很多免费代码分享~ 目录 效果展示&#xff1a; 改进策略详解&#…

C语言——指针的进阶——第1篇——(第26篇)

坚持就是胜利 文章目录 一、字符指针1、面试题 二、指针数组三、数组指针1、数组指针的定义2、&数组名 VS 数组名3、数组指针的使用&#xff08;1&#xff09;二维数组传参&#xff0c;形参是 二维数组 的形式&#xff08;2&#xff09;二维数组传参&#xff0c;形参是 指针…

django的模板渲染中的【高级定制】:按数据下标id来提取数据

需求&#xff1a; 1&#xff1a;在一个页面中显示一张数据表的数据 2&#xff1a;不能使用遍历的方式 3&#xff1a;页面中的数据允许通过admin后台来进行修改 4&#xff1a;把一张数据表的某些内容渲染到[xxx.html]页面 5&#xff1a;如公司的新商品页面&#xff0c;已有固定的…

python进阶:可迭代对象和迭代器

一、Iterable&#xff08;可迭代对象&#xff09; 1、可迭代对象&#xff1a;能够进行迭代操作的对象。 可以理解为&#xff1a;能够使用for循环遍历的都是可迭代对象&#xff1b;**所有的可迭代对象&#xff0c;偶可以用内置函数iter转换为迭代器** 2、可迭代对象包括&…

Linux文本处理三剑客:awk(常用匹配模式)

在Linux操作系统中&#xff0c;grep、sed、awk被称为文本操作“三剑客”&#xff0c;上三期中&#xff0c;我们将详细介绍grep、sed、awk的基本使用方法&#xff0c;希望能够帮助到有需要的朋友。 1、前言 awk作为一门编程语言还有很多内容&#xff0c;我们继续学习awk。 网…

快速解决maven依赖冲突

我们在开发过程中经常出现maven依赖冲突&#xff0c;或者maven版本不匹配的情况&#xff0c;我们可以使用阿里云原生脚手架来做maven管理&#xff0c;添加需要的组件&#xff0c;然后点击获取代码&#xff0c;就可以获得对应的依赖文件。

【C语言】InfiniBand驱动mlx4_init和mlx4_cleanup

一、中文注释 Linux内核模块的初始化和清理过程&#xff0c;针对一个称为mlx4的网络设备驱动。以下是代码的逐行中文注释&#xff1a; static int __init mlx4_init(void) {int ret;if (mlx4_verify_params())return -EINVAL; // 检查设备参数是否有效&#xff0c;无效则返回…

.idea文件详解

.idea文件的作用&#xff1a; .idea文件夹是存储IntelliJ IDEA项目的配置信息&#xff0c;主要内容有IntelliJ IDEA项目本身的一些编译配置、文件编码信息、jar包的数据源和相关的插件配置信息。一般用git做版本控制的时候会把.idea文件夹排除&#xff0c;因为这个文件下保存的…