vuex详解及模块化

私人博客

许小墨のBlog —— 菜鸡博客直通车

系列文章完整版,配图更多,CSDN博文图片需要手动上传,因此文章配图较少,看不懂的可以去菜鸡博客参考一下配图!

系列文章目录

前端系列文章——传送门
后端系列文章——传送门



vuex的使用

vuex是什么?

vue项目中的数据库,其中的数据是不持久的,在多个组件要共用一些临时数据的时候使用vuex。

依赖第三方模块:

npm i vuex@3

配置:在src下新建了store文件夹,其中新建了index.js

import Vue from 'vue'
import vuex from 'vuex'
Vue.use(vuex)
const store = new vuex.Store({
    
    
    // 定义数据
    state: {
    
    
        num1: 5
    }
})
export default store

在根组件中使用store,在main.js中:

import store from '@/store'

new Vue({
    
    
    store
})

使用:

模板中使用:

{
   
   {$store.state.num1}}

在逻辑代码中使用:

console.log(this.$store.state.num1)

如果要将vuex中的数据放在自己组件中,当做自己这个组件的数据使用 的时候:

<script>
    // 导入state数据
    import {
      
      mapState} from 'vuex'
    export default {
      
      
        computed:{
      
      
            ...mapState(['num1'])
        }
    }
</script>

此时当前组件就有计算属性 num1 了。

vuex

vuex中5个属性:

state

mutations

actions

getters

modules - 模块化管理数据

modules: {
    
    
    命名空间名字: 数据,
    空间名字: 数据
}

数据是通过导入进来的,被导入的文件:

export default {
    
    
    namespaced: true,
    state: {
    
    },
    getters: {
    
    },
}

state使用:

直接使用

模板中

{
   
   {$store.state.空间名字.数据}}

逻辑代码中

this.$store.state.空间名字.数据

将数据放在自己组件中:

import {
    
    mapState} from 'vuex'

computed: {
    
    
    ...mapState('空间名字', ['数据名字'])
}

getters使用:

直接使用

模板中

{
   
   {$store.getters['空间名字/数据']}}

逻辑代码中:

this.$store.getters['空间名字/数据']

将getters当做自己组件的数据:

import {
    
    mapGetters} from 'vuex'

computed: {
    
    
    ...mapGetters('空间名字', ['数据名字'])
}

mutations中定义方法,跟以前的定义方式一样

直接使用

this.$store.commit('空间名称/方法名称')

当做自己方法使用

// 导入
import {
    
    mapMutations} from 'vuex'
// 展开在methods中
methods: {
    
    
    ...mapMutations('空间名称', ['方法名称'])
}

actions中定义异步方法,跟以前的方法一样

直接使用:

this.$store.dispatch('空间名称/方法名称')

当做自己的方法使用

// 导入
import {
    
    mapActions} from 'vuex'

// 展开在自己的方法中
methods: {
    
    
    ...mapActions('空间名称', ['方法名称'])
}

本博文缺失大量图片,严重影响内容完整性以及阅读体验,完整内容请前往本人菜鸡博客——许小墨のBlog

猜你喜欢

转载自blog.csdn.net/qq_60306931/article/details/130692100