Vuex使用教程

辰漪
2021-11-09 / 0 评论 / 294 阅读 / 正在检测是否收录...

一、Vuex简述

Vuex其实就是一个状态管理工具,所谓的状态,就是数据,通过这个工具进行管理某些数据。当多个组件都需要同一个数据时,可以将这个数据交给Vuex进行统一的管理,组件可以直接引用这个数据,避免了组件间繁琐的层层传递的情况。

二、Vuex核心

Vuex有五大核心,state,getter,mutation,action,module。state用来存放要被管理的数据,getter相当于computed计算属性,mutation中用来定义要修改state中数据的方法,action中用来定义异步的一些方法,module可以将多个store分成一个一个的模块。

三、Vuex使用

 1. 在vue项目中使用Vuex时,需要先安装Vuex插件,并且注册,一般情况下都会在,在src下新创建一个store文件夹,下边有一个index.vue,在这个文件中创建store容器实例.。

// 1. 安装插件
npm install vuex --save
// 2. 注册插件
import Vue from 'vue' 
import Vuex from 'vuex'
Vue.use(Vuex)

 2. 创建vuex实例,在vuex上提供了一个Store()方法,用来创建实例,将其命名为store,意为仓库的意思。在Vuex.Store()中传一个配置对象,配置对象中包括上述的五大核心,如果用不到,也可以不做配置。

const store = new Vuex.Store({
    state: {num: 2}, // 存放数据
    getters: {}, // 计算属性
    mutations: {}, // 修改state中数据的一些方法
    actions: {}, // 异步方法
    modules: {} // store模块
})
export default store

 3. 在入口文件main.js中引入store。

// main.js
import Vue from 'vue'
import App from './App'
import store from './store/index.vue' // 简写 import store from './store'

Vue.config.productionTip = false

new Vue({
    el: '#app',
   store: store, // es6 简写  直接写 store 属性名和变量名相同
   render: h => h(App)
})

 4. 在页面中如何使用store中的数据?在使用vuex中的数据之前,先使用import导入写好的store。组件中在插值表达式中使用$store.state.num获取store中num的数据。

<template>
    <div>
        <h2>{{ $store.state.num }}</h2>
    </div>
</template>

四、mapState,mapMutations,mapGetters,mapActions映射

1. // 先从vuex中结解构出四个方法 
import {mapState, mapMutations, mapGetters, mapActions} from 'vuex'
2. // 在computed计算属性中映射state数据和getters计算属性
computed: {
    ...mapState('模块名', ['name', 'age'])
    ...mapGetters('模块名', ['getName'])
}
3. // 在methods方法中映射mutations和actions方法
methods: {
    ...mapMutations('模块名', ['方法名1','方法名2'])
    ...mapActions('模块名', ['方法名1','方法名2'])
}
4. 这些数据和方法都可以通过this来调用和获取

以上就是vuex大致的使用方法
全文转自: 辰漪博客

1
选择打赏方式:
微信

评论 (0)

取消