一文学会Vuex4-看不懂你给我一拳

261 阅读3分钟

Vuex4安装并注册

1.安装

npm i vuex

2. 创建store文件:src/store/index.js

import { createStore } from "vuex"
const store = createStore({
    state:{
    
    },
    getters:{
    
    },
    mutations:{
    
    },
    actions:{
    
    }
})
export default store

3. main.js配置

import { createApp } from 'vue'
import App from './App.vue'
//1.导入store文件
import store from "./store/index"
//2.全局注册
createApp(App).use(store).mount('#app')

经过上面的配置,你已经可以成功使用Vuex了。

Vuex的使用

state

state是用于保存vuex数据的唯一位置。

//store/index.js
import { createStore } from "vuex"
const store = createStore({
    state:{
        age:22,
        name:"xiaoming"
    }
})
export default store

组件中使用vuex数据方式一:

//App.vue
<template>
    <div>获取数据方式一:{{store.state.name}}</div>
</template>
<script setup>
    import {useStore} from "vuex"
    const store = useStore()
    
</script>

页面结果:
获取数据方式一:xiaoming

组件使用Vuex数据方式二:

  //App.vue
<template>
    <div>获取数据方式二:{{name}}</div>
</template>
<script setup>
    import {useStore} from "vuex"
    import {computed} from "vue"
    const store = useStore()
    const name = computed(()=>{
        return store.state.name
    )}
</script>

页面结果:
获取数据方式二:xiaoming

总结:上面两种方式都可以使用vuex数据,同时让vuex仓库的数据具备响应式,如果对store的数据使用了ref或者reactive包裹,store的响应式会丢失。因此这两种导入是比较常用的方式。

getters

getters是对state数据的修饰,只能读取state的数据,无法修改。功能和vue的computed类似。其中getters内部方法的参数就是state的引用。

//store/index.js 
import { createStore } from "vuex" 
const store = createStore({ 
    state:{ 
        age:22, 
        name:"xiaoming"
    },
    getters:{
        dealName(state) {
            return state.name + "!!!"
        }
    }
})

组件中使用getters数据: store.getters.方法名

//App.vue
<template>
    <div>state:{{nameState}}</div>
    <div>getters:{{nameGetters}}</div>
</template>
<script setup>
    import {useStore} from "vuex"
    import {computed} from "vue"
    const store = useStore()
    const nameState = computed(()=>{
        return store.state.name
    )}
    const nameGetters = computed(()=>{
        return store.getters.dealName
    })
</script>

页面结果:
state: xiaoming
getters:xiaoming!!!

mutations

mutations作用就是修改state的数据,并且它只能用于处理同步代码的修改。如果是异步的修改,需要使用actions。其中mutations内部方法的第一个参数是state,第二个参数是组件传递的数据。

//store/index.js 
import { createStore } from "vuex" 
const store = createStore({ 
    state:{ 
        age:22, 
        name:"xiaoming"
    },
    getters:{
        dealName(state) {
            return state.name + "!!!"
        }
    },
    mutations:{
        changeName(state,payload) {
            state.name = payload
        }
    }
})

组件中使用mutataions:store.commit(mutataions中方法,传递的数据)

 //App.vue
<template>
    <div>state:{{nameState}}</div>
    <div @click='change'>点击修改name</div>
</template>
<script setup>
    import {useStore} from "vuex"
    import {computed} from "vue"
    const store = useStore()
    const nameState = computed(()=>{
        return store.state.name
    )}
    const change = ()=> {
        store.commit("changeName","xiaogang")
    }
</script>

页面结果:
state: xiaoming
点击修改按钮后显示 state:xiaogang

actions

actions就是专门通过异步代码修改state数据。其和mutations基本一样,第一个参数是state,第二个参数就是组件传递的数据。

//store/index.js 
import { createStore } from "vuex" 
const store = createStore({ 
    state:{ 
        age:22, 
        name:"xiaoming"
    },
    getters:{
        dealName(state) {
            return state.name + "!!!"
        }
    },
    mutations:{
        changeName(state,payload) {
            state.name = payload
        }
    },
    actions:{
        changeAsyncName(state,payload){
            //模拟异步
            setTimeout(()=>{
                state.name = payload
            },20000)
        }
    }
})

组件中使用actions修改数据:store.dispatch(actions中方法,传递的数据)

 //App.vue
<template>
    <div>state:{{nameState}}</div>
    <div @click='change'>点击修改name</div>
</template>
<script setup>
    import {useStore} from "vuex"
    import {computed} from "vue"
    const store = useStore()
    const nameState = computed(()=>{
        return store.state.name
    )}
    const change = ()=> {
        store.dispatch("changeAsyncName","xiaogang")
    }
</script>

页面结果:
state: xiaoming
点击修改按钮2s后显示 state:xiaogang

Vuex的模块化

模块化可以简单理解成不同的小房间,每个房间有自己独立的数据,各个模块使用各自的数据。

模块化配置

image.png

观察vuex存储目录是storeVux。首先我们创建一个根文件,用于保存所有的模块。我这里就是index.js。此处我定义了两个模块一个是school,另一个是user。

1.storeVuex/index.js

    import { createStore } from "vuex"
    import school from "./modules/school/index"
    import user from "./modules/user/index"
    //模块化使用
    const store = createStore({
      modules: {
        school,
        user
      }
    })
    export default store
    

2.main.js(按照路径正常导入vuex根文件)

    import { createApp } from 'vue'
    import App from './App.vue'
    //导入根文件
    import store from "./storeVuex/index
    createApp(App).use(store).mount('#app')
    
 

3.school和user模块定义

  //school和user各自在自己的index.js定义自己模块的数据和方法
  //如下是 storeVuex/modules/user/index.js(user模块的数据)
  export default {
  namespaced:true,
  state:{
      name:"dzp"
  },
  actions:{
      changeName(state,payload){
          setTimeout(()=>{
              state.name = payload
          },2000)
      }
  }, 
  getters:{
      dealName(state) {
          return state.name + "!!!"
      }
  },
  mutations:{
      changeName(state,payload){
          state.name = payload
      }
  }
}

模块化数据的使用

state数据使用:store.state.模块名.数据

  <script setup>
      import {useStore} from "vuex"
      import {computed} from "vue"
      const store = useStore()

      const userName = computed(()=>{
        return store.state.user.name
      })
  </script>
  
  <template>
      <div>{{userName}}</div>
  </template>
  
  
  页面输出dzp
  

getters数据使用:store.getters['模块名/方法名'] 。是不是感觉很奇葩,可恶,这个获取getters的定义属实恶心。

  <script setup>
      import {useStore} from "vuex"
      import {computed} from "vue"
      const store = useStore()

      const userName = computed(()=>{
        return store.getters["user/dealName"]
      })
  </script>
  
  <template>
      <div>{{userName}}</div>
  </template>
  
  页面输出 dzp!!!
  

mutations修改数据:store.commit("模块名/方法名",data)

  <script setup>
      import {useStore} from "vuex"
      import {computed} from "vue"
      const store = useStore()

      const userName = computed(()=>{
        return store.state.user.name
      })
      const change = ()=> {
          store.commit("user/changeName","hhhh")
      }
  </script>
  
  <template>
      <div>{{userName}}</div>
      <div @click='change'>修改名字</div>
  </template>
  
  页面先显示dzp.点击修改名字后输出 hhhh
  
  

actions修改数据:store.dispatch("模块名/方法名",data)

 <script setup>
      import {useStore} from "vuex"
      import {computed} from "vue"
      const store = useStore()

      const userName = computed(()=>{
        return store.state.user.name
      })
      const change = ()=> {
          store.dispatch("user/changeName","hhhh")
      }
  </script>
  
  <template>
      <div>{{userName}}</div>
      <div @click='change'>修改名字</div>
  </template>
  
  页面先显示dzp.点击修改名字后2s显示 hhhh

结语

如果我的文章对你有帮助,希望你高抬贵手,点个赞再走也不迟,你的支持就是我的最大动力。如果感觉有问题,欢迎线上给我一拳。