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

news2024/9/23 17:25:40

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.coloradmin.cn/o/1488300.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

“比特币暴拉冲破6.5万美元”!超罕见指标揭示牛市信号,18万美元目标能否实现?

比特币&#xff08;BTC&#xff09;周末持续在6.2万美元反复震荡之后&#xff0c;今&#xff08;4&#xff09;晨再次强势拉涨&#xff0c;早上8&#xff1a;45左右最高触及64268美元&#xff0c;随后插针盘整&#xff0c;下午5点30分左右突破65500美元&#xff0c;再创今年新高…

第七届电路,系统与仿真国际会议(ICCSS 2024)即将召开!

2024年第七届电路&#xff0c;系统与仿真国际会议&#xff08;ICCSS 2024&#xff09;将于5月17-19日马来西亚博特拉大学举办。本届会议由马来西亚博特拉大学和中国东南大学协办&#xff0c;电机与电子工程系主办。ICCSS 2024 热烈欢迎所有来自电路、系统和仿真等相关领域的研究…

Java基于springboot的课程作业管理系统

摘 要 随着科学技术的飞速发展&#xff0c;社会的方方面面、各行各业都在努力与现代的先进技术接轨&#xff0c;通过科技手段来提高自身的优势&#xff0c;课程作业管理系统当然也不能排除在外。课程作业管理系统是以实际运用为开发背景&#xff0c;运用软件工程原理和开发方法…

书生浦语全链路开源体系

推荐阅读论文 A Survey Of Large Language Models 书生浦语开源的模型 从模型到应用 书生浦语开源体系 书生万卷开源数据集 除此之外还有OpenDataLab国内数据集下载网站。 预训练框架InterLM-Train 微调框架XTuner 评测工具体系 国内外常见的大语言模型评测基准&#xff1a…

如何扫码查看图片信息?图片放到二维码展示的在线教学

现在通过扫码来查看物品图片是很常用的一种方式&#xff0c;将物品不同角度的图片存入一张二维码后&#xff0c;用户只需要扫描这张二维码图片&#xff0c;就可以了解物品预览图及其他信息。常用的图片格式比如jpg、png、gif都可以放到二维码中显示&#xff0c;那么具体该怎么做…

如何在飞书接入ChatGPT并结合内网穿透实现公网远程访问智能AI助手

文章目录 前言环境列表1.飞书设置2.克隆feishu-chatgpt项目3.配置config.yaml文件4.运行feishu-chatgpt项目5.安装cpolar内网穿透6.固定公网地址7.机器人权限配置8.创建版本9.创建测试企业10. 机器人测试 前言 在飞书中创建chatGPT机器人并且对话&#xff0c;在下面操作步骤中…

column ‘_id‘ does not exist

最近把 csv 导入 SQLite 给 CursorAdapter 使用出现了这个莫名其妙的错误。 java.lang.IllegalArgumentException: column _id does not exist-CSDN博客 查找资料才明白&#xff1a;CursorAdapter 使用的数据库中必须有 _id 这个字段。 好吧&#xff0c;导入的数据库增加 _i…

为何代理IP的稳定性不如有线IP?

代理IP与网线IP的稳定性之间存在差异的原因在于它们的工作机制和服务环境的不同。以下是代理IP不如网线IP稳定的一些主要原因&#xff1a; 1. 服务提供商的质量&#xff1a; - 动态分配&#xff1a;代理IP通常是动态分配的&#xff0c;这意味着每次请求或每隔一段时间&#xff…

2.00001《Postgresql内幕探索》走读 之 查询优化

文章目录 1.1 概述1.1.1 Parser1.1.2 分析仪/分析器1.1.3 Rewriter1.1.4 Planner和Executer 1.2 单表查询的成本估算1.2.1 顺序扫描1.2.2 索引扫描1.2.3 排序 1.3 .创建单表查询的计划树1.3.1 预处理1.3.2 获取最便宜的访问路径示例1示例二 1.3.3 创建计划树示例1例二 1.4 EXEC…

python学习27

前言&#xff1a;相信看到这篇文章的小伙伴都或多或少有一些编程基础&#xff0c;懂得一些linux的基本命令了吧&#xff0c;本篇文章将带领大家服务器如何部署一个使用django框架开发的一个网站进行云服务器端的部署。 文章使用到的的工具 Python&#xff1a;一种编程语言&…

Redis安装与数据类型及常用命令

一、关系数据库和非关系型数据库1、关系型数据库2、非关系型数据库3、非关系型数据库产生背景4、关系型数据库和非关系型数据库区别5、为什么非关系型数据库能提升访问速度&#xff1f; 二、Redis简介1、Redis 的优点2、使用场景3、哪些数据适合放入缓存中&#xff1f;4、Redis…

芯片ERP:应用广泛的领域及其影响

在现代科技快速发展的时代&#xff0c;芯片ERP(企业资源规划)已成为许多行业不可或缺的工具。这种集成了先进技术和先进管理理念的系统&#xff0c;极大地提高了企业的运营效率和竞争力。那么&#xff0c;芯片ERP主要应用在哪些领域呢?本文将为您一一揭晓。 一、电子制造行业 …

啤酒:精酿啤酒与烤串的夜晚滋味

夏日的夜晚&#xff0c;微风拂面&#xff0c;星光璀璨。此时&#xff0c;能抚慰人心的莫过于与三五好友围坐一起&#xff0c;享受烤串与Fendi Club啤酒的美味。这种滋味&#xff0c;不仅仅是味蕾的盛宴&#xff0c;更是心灵的满足。 Fendi Club啤酒&#xff0c;每一滴都蕴含着大…

python标识符、变量和常量

一、保留字与标识符 1.1保留字 保留字是指python中被赋予特定意义的单词&#xff0c;在开发程序时&#xff0c;不可以把这些保留字作为变量、函数、类、模块和其它对象的名称来使用。 比如&#xff1a;and、as、def、if、import、class、finally、with等 查询这些关键字的方…

指针习题二

使用函数指针实现转移表 #include <stdio.h> int add(int a, int b) {return a b; } int sub(int a, int b) {return a - b; } int mul(int a, int b) {return a * b; } int div(int a, int b) {return a / b; } int main() {int x, y;int input 1;int ret 0;int(*p[…

SwiftUI 如何在运行时从底层动态获取任何 NSObject 对象实例

概览 众所周知,SwiftUI 的推出极大地方便了我们这些秃头码农们搭建 App 界面。不过,有时我们仍然需要和底层的 UIKit 对象打交道。比如:用 SwiftUI 未暴露出对象的接口改变视图的行为或外观。 从上图可以看到,我们 SwiftUI 代码并没有设置视图的背景色,那么它是怎么变成绿…

pydub、playsound播放声音;gradio、streamlit页面播放声音;gradio 页面图像、视频及调用摄像头

1、pydub from pydub import AudioSegment from pydub.playback import playsong AudioSegment.from_wav(r"C:\Users\loong\Downloads\zh.wav") play(song)2、playsound from playsound import playsoundplaysound(r"voice.wav")3、streamlit import s…

Docker创建Reids容器

1.默认拉取Redis最新镜像版本 docker pull redis 2.下载redis配置文件 https://download.redis.io/releases/ 3.下载配置文件后手动更改密码&#xff0c;链接时间等信息 绑定地址&#xff08;bind&#xff09;&#xff1a;默认情况下&#xff0c;Redis 只会监听 localhost…

如何做代币分析:以 LEO 币为例

作者&#xff1a; lesleyfootprint.network 编译&#xff1a;cicifootprint.network 数据源&#xff1a;LEO 代币仪表板 &#xff08;仅包括以太坊数据&#xff09; 在加密货币和数字资产领域&#xff0c;代币分析起着至关重要的作用。代币分析指的是深入研究与代币相关的数…

如何实现飞书与金蝶无缝对接,提升业务效率与客户满意度?

一、客户介绍 某贸易有限公司是一家专业从事进口葡萄酒和高端烈酒销售的企业。在市场竞争日益激烈的今天&#xff0c;该公司始终坚持以客户为中心&#xff0c;以市场为导向&#xff0c;不断创新和进步。公司不仅注重传统销售渠道的拓展&#xff0c;还积极拥抱互联网&#xff0…