Vuex学习笔记

2021-04-09  本文已影响0人  幽小鬼

用了好久vuex没有记录过,重新再学一遍并做一下笔记。

1 Vuex概述

1.1 组件之间共享数据的方式

父向子传值:v-bind 属性绑定
子向父传值:v-on 事件绑定
兄弟组件传值: EventBus

1.2 Vuex是什么

Vuex是实现组件全局状态(数据)管理的一种机制,可以方便的实现组件之间数据的共享。

1.3 使用Vuex的好处

1.4 什么样的数据适合存储到Vuex中

一般情况向下,只有组件间共享的内容才存储到vuex中,对于组件中的私有数据,依旧存储在组件自身的data

2 Vuex的基本使用

2.1 安装vuex依赖包

npm install vuex --save

2.2 导入vuex包

import Vuex from 'vuex'
//挂载Vuex
Vue.use(Vuex)

2.3 创建store对象

//创建VueX对象
const store = new Vuex.Store({
    state: {
        //存放的键值对就是所要管理的状态
        name: 'helloVueX'
    }
})

2.4 将store对象挂载到vue实例中

在根目录底下的main.js的文件中:

import store from './store'
new Vue({
  el: '#app',
  // 将创建的数据共享对象挂载到这个vue实例中
  store,
  render: h => h(App)
})

3 Vuex核心概念

3.1 State

State提供唯一的公共数据源,所有共享的数据源都要统一放到StoreState中进行存储。
组件访问State中数据方式:

方式一

this.$store.state.全局数据名称

方式二

// 从vuex中按需导入mapState
import { mapState } from 'vuex'

通过导入的mapState函数,将当前函数需要的全局数据,映射为当前组件的computed计算属性:

computed: {
  ...mapState(['name'])
}

然后在当前组件就可以直接使用this.name

3.2 Mutation

Mutation用于变更Store中的数据。

mutations使用方法

mutations方法都有默认的形参:
([state] [,payload])

定义Mutation

const store = new Vuex.Store({
    state: {
        name: 'helloVueX'
    },
    mutations: {
        edit (state, name) {
            // 变更状态
            state.name = name
        }
    }
})

方法一

在组件中使用commit函数调用这个mutation

this.$store.commit('edit', '111')

方法二

// 从vuex中按需导入mapMutitions
import { mapMutations } from 'vuex'

通过导入的mapMutations函数,将需要的mutations函数映射为当前组件的methods方法:

methods: {
  ...mapMutations(['edit'])
}

然后在当前组件可以直接调用方法this.edit('111')

3.3 Action

Action用于处理异步任务。
如果通过异步操作变更数据,必须使用Action,而不能使用Mutation,但是在Action中还是要通过触发Mutation的方式间接变更数据。

actions使用方法

Actions中的方法有两个默认参数:
([context] [,payload])

比如执行setTimeout异步操作:

actions:{
    aEdit(context, payload) {
        setTimeout(() => {
            // 只有mutations中定义的函数才有权利修改state中的数据
            context.commit('edit', payload)
        }, 1000)
    }
}

方法一

在组件中调用异步方法,使用dispatch函数来触发action

this.$store.dispatch('aEdit', '111')

方法二

// 从vuex中按需导入mapActions
import { mapActions } from 'vuex'

通过导入的mapActions函数,将需要的actions函数映射为当前组件的methods方法:

methods: {
  ...mapActions(['aEdit'])
}

然后在当前组件可以直接调用方法this.aEdit('111')

3.4 Getter

Getter用于对Store中的数据进行加工处理形成新的数据。

Getters使用方法

Getters中的方法有两个默认参数

getters:{
    name1(state) {
        return state.name
    },
    name2(state, getters) {
        return getters.name1 + state.name
    }  
}

方法一

this.$store.getters.名称

方法二

// 从vuex中按需导入mapGetters
import { mapGetters } from 'vuex'

通过导入的mapGetters函数,将当前函数需要的全局数据,映射为当前组件的computed计算属性:

computed: {
  ...mapGetters(['name1'])
}
上一篇 下一篇

猜你喜欢

热点阅读