Vuex 常规用法

背景

很多时候我们已经熟悉了框架的运用,但是有时候就是忘了怎么用

所以这里想记下大部分的框架使用方法,方便使用的时候拷贝

一、安装

npm 方式

npm install vuex --save

yarn 方式

yarn add vuex

二、vuex 用法

1、引入以及安装

import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const store = new Vuex.Store({
    state: {},
    getters: {},
    mutations: {},
    actions: {}
})
new Vue({
    // 把 store 提供给 store 选项,
    // Vue 最初实例化的时候将 store 的实例注入到所有的子组件,意味着子组件可以使用 this.$store 调用 store 实例
    store
})

2、正常使用

(1)、state

(2)、getters

(3)、mutations

(4)、actions

const store = new Vuex.Store({
    state: {
        count: 0,
        todos: [
            { id: 1, done: true },
            { id: 2, done: false }
        ]
    },
    // 是 state 的 computed
    getters: {
        doneTodos: (state, getters) => {
            return state.todos.filter(todo => todo.done)
        },
        doneTodoCount: (state, getters) => {
            return getters.doneTodos.length
        }
    },
    // mutation 必须是同步函数,以便追踪状态(编写规范如此,非强制)
    // 可以使用 state.obj = { ...state.obj, newProp: 1 } 进行值的替换(新对象替换旧对象,支持增加新属性)
    mutations: {
        mutationChangeState__increment(state, payload) {
            // payload: 调用该方法时,传递进来的参数
            state.count++
        }
    },
    // mutation 里不允许的异步操作,可以放在 action 里面
    actions: {
        // 1、普通操作
        actionCallMutation__mutationChangeState__increment(context) {
            // context 是与 store 实例具有相同方法和属性的对象
            context.commit('mutationChangeState__increment')
        },
        // 解构 context 使用
        actionCallMutation__mutationChangeState__increment({ state, commit, dispatch, getters }) {
            commit('mutationChangeState__increment')
        },

        // 2、Promise 应用
        // 异步操作转同步 Promise 1
        actionCallMutation__mutationChangeState__increment({ state, commit, dispatch, getters }) {
            return new Promise((resolve, reject) => {
                // ...
                // resolve()
                // reject()
            })
        },
        // 异步操作转同步 Promise 2
        actionCallMutation__mutationChangeState__increment2({ state, commit, dispatch, getters }) {
            dispatch('actionCallMutation__mutationChangeState__increment').then(() => {
                // ...
            })
        },

        // 3、async/await 应用
        // 异步操作转同步 async 1
        async actionCallMutation__mutationChangeState__increment({ state, commit, dispatch, getters }) {
            await getData()
        },
        // 异步操作转同步 async 2
        async actionCallMutation__mutationChangeState__increment({ state, commit, dispatch, getters }) {
            await dispatch('actionCallMutation__mutationChangeState__increment')
            // dosomething...
        },
    }
})
export default store

3、存在子模块

3.1、modulesA

// 注意!注意!注意!
// modulesA 中的
// Astate,Agetters,Amutations,Aactions 应该为
// state,getters,mutations,actions
// 我这里是为了区分子模块和根模块才这么命名
const modulesA = {
    // 1、在 namespaced 为 false 的情况下:
    // 默认情况下,模块内部的 action、mutation、getter
    // 分别和根模块的 action、mutation、getter 共享一个命名空间
    // 即 Vuex 实例的 _getters、_mutations、_actions
    // store: {
    //     _getters: {},
    //     _mutations: {},
    //     _actions: {}
    // }

    // (1)、如果子模块的 getters 定义了和根模块相同的 getters,将会报错提示定义了相同的变量名
    // store: {
    //     _getters: {
    //         getter1: 0,
    //         getter2: {},
    //     }
    // }

    // (2)、如果子模块的 mutation 定义了和根模块相同的的 mutation,Vue 将该同名 mutation 转换成以该 mutation 名称为变量名的数组,并存储这两个 mutation 函数
    // 先执行根模块的 mutation ,然后执行子模块的 mutation
    // store: {
    //     _mutation: {
    //         mutationRepeatName: [function(){}, function(){}],
    //         otherMutation: function(){}
    //     }
    // }

    // 2、在 namespaced 为 true 的情况下,不存在覆盖根模块的情况
    // (1)、如果子模块的 getters 定义了和根模块相同的 getters,不会报错,会加入模块名作为变量名前缀
    // store: {
    //     _getters: {
    //         a/getter1: 0,
    //         getter1: {},
    //     }
    // }

    // (2)、如果子模块的 mutation 定义了和根模块相同的的 mutation,会加入模块名作为 mutation 名前缀
    // store: {
    //     _mutation: {
    //         a/mutationRepeatName: function(){},
    //         mutationRepeatName: function(){}
    //     }
    // }

    // 3、启用了命名空间的 getter 和 action 会收到局部化的 getter,dispatch 和 commit
    // 所以 namespaced 的改变,不影响模块代码
    namespaced: false,

    // 子模块的 Astate 直接附加到根模块的 state
    // 在根模块的 state 中, 以子模块名为 key,作为 state 的一个属性存在
    // state: {
    //     a: { // 这里即子模块的 Astate

    //     }
    // }
    Astate: {
        count: 0,
        todos: [
            { id: 1, done: true },
            { id: 2, done: false }
        ]
    },
    Agetters: {
        AdoneTodos: (Astate, Agetters, rootState, rootGetters) => {
            // rootState 为根模块的 state
            // rootGetters 为根模块的 rootGetters
            return Astate.todos.filter(todo => todo.done)
        },
    },
    Amuattions: {
        mutationChangeState__increment(Astate, payload) {
            // payload: 调用该方法时,传递进来的参数
            Astate.count++
        }
    },
    Aactions: {
        actionCallMutation__mutationChangeState__increment({ Astate, Acommit, Adispatch, Agetters, rootState, rootGetters }) {
            // rootState 为根模块的 state
            Acommit('mutationChangeState__increment')

            // 调用时,传递第三个参数{ root: true }, 可以访问根模块的 actions: someMutation
            Acommit('someMutation', null, { root: true })
        },
        someRootAction: {
            root: true, // 设置 root 属性为 true,可以将 someRootAction 注册在根模块
            handler (namespacedContext, payload) { ... } // -> 'someRootAction'
        }
    }
}

3.2、使用子模块

const store = new Vuex.Store({
    modules: {
        a: modulesA
    },
    state: {},
    // 是 state 的 computed
    getters: {},
    // mutation 必须是同步函数,以便追踪状态(编写规范如此,非强制)
    // 可以使用 state.obj = { ...state.obj, newProp: 1 } 进行值的替换(新对象替换旧对象,支持增加新属性)
    mutations: {},
    // mutation 里不允许的异步操作,可以放在 action 里面
    actions: {}
})
export default store

三、组件内常用操作

1、在组件中使用实例调用

// 调用 modulesA
// 1、调用 state
this.$store.state.a.todos
// 2、调用 getter
this.$store.getters.AdoneTodos // namespaced: false
this.$store.getters['a/AdoneTodos'] // namespaced: true
// 3、调用 mutation
this.$store.commit('AmutationChangeState__increment') // namespaced: false
this.$store.commit('a/AmutationChangeState__increment') // namespaced: true
// 4、调用 action
this.$store.dispatch('AmutationChangeState__increment') // namespaced: false
this.$store.dispatch('a/AmutationChangeState__increment') // namespaced: true

// state
this.$store.state['属性key']
// getters
this.$store.getters['属性key']
// 调用 mutation
this.$store.commit('mutationChangeState__increment', payload)
this.$store.commit({ // 对象风格调用,整个对象都将作为 payload 传递给 mutation 方法
    type: 'mutationChangeState__increment',
    payload1: '',
    payload2: ''
})
// 调用 action
this.$store.dispatch('actionCallMutation__mutationChangeState__increment')
this.$store.dispatch({ // 对象风格调用,整个对象都将作为 payload 传递给 dispatch 方法
    type: 'actionCallMutation__mutationChangeState__increment',
    payload1: '',
    payload2: ''
})

2、在组件中使用辅助函数调用

// 辅助函数
import { mapState, mapGetters, mapMutations, mapActions, createNamespacedHelpers  } from 'vuex'
// or
const { mapState, mapGetters, mapMutations, mapActions, createNamespacedHelpers } = createNamespacedHelpers('子命名空间')
export default {
    created() {
        // 使用
        // state
        console.log(this.stateName1, this.stateName2)
        // getter
        console.log(this.getterName1, this.getterName2)

        // mutation
        this.mutationName1()
        this.mutationName2()
        // action
        this.actionName1()
        this.actionName2()
    },
    computed: {
        // mapState
        // 数组用法
        ...mapState(['stateName1', 'stateName2']),
        // 对象用法
        ...mapState({
            stateName3: state => state.stateName3,
            stateName4_alias: state => state.stateName4,
            stateName5_alias: 'stateName5', // 此处 'stateName5'(注意是字符串) 等于 state => state.stateName5
            stateName6_resolve: state => { // 获取经过处理的值
                return state.count + this.stateName1
            }
        }),

        // mapGetters
        // 数组用法
        ...mapGetters(['getterName1', 'getterName2'])
        // 对象用法
        ...mapGetters({
            getterName3_alias: 'getterName3'
        })
    },
    methods: {
        // mapMutations
        // 数组用法
        ...mapMutations(['mutationName1', 'mutationName2']),
        // 对象用法
        ...mapMutations({
            mutationName3_alias: 'mutationName3'
        }),

        // mapActions
        // 数组用法
        ...mapActions(['actionName1', 'actionName2']),
        // 对象用法
        ...mapActions({
            actionName3_alias: 'actionName3'
        }),
    }
}

原文地址:https://www.cnblogs.com/linjunfu/p/11643437.html

时间: 2024-08-30 07:50:25

Vuex 常规用法的相关文章

flush 的常规用法:

flush  logs : 刷新二进制日志文件 flush  PRIVILEGES:刷新权限,修改权限或密码后,需要使用到该命令 flush tables:关闭所有表,并清空缓存中的类容 . flush tables with read lock:关闭所有打开的表,并且对所有DB中的表添加一个读锁, 直到显示执行unlock tables .该命令常用语备份数据. flush master :删除所有二进制日志索引文件中的二进制日志文件,重置二进制日志文件的索引文件为空, 创建一个新的二进制日志

RE正则的常规用法

1.re的简介 使用python的re模块,尽管不能满足所有复杂的匹配情况,但足够在绝大多数情况下能够有效地实现对复杂字符串的分析并提取出相关信息.python 会将正则表达式转化为字节码,利用 C 语言的匹配引擎进行深度优先的匹配. 复制代码 代码如下: import re print re.__doc__ 可以查询re模块的功能信息,下面会结合几个例子说明. 2.re的正则表达式语法 正则表达式语法表如下: 语法 意义 说明 "." 任意字符   "^" 字符串

vi 常规用法

vi 的用法 一.移动光标 h 向右移动 l 向左移动 j 向下移动 k 向上移动 二.以单词为单位移动 w 下一个单词词首 e 下一个单词词尾 b 当前或者前一个单词的词首 三.行内跳转 0 绝对行首 ^ 行首的第一个非空白字符 $ 绝对行尾 四.行间跳转 #G 跳转到第#行 G 最后一行 五.翻屏操作 ctrl+f 向文件尾部翻一屏 ctrl+b 向上翻一屏 ctrl+d 向下翻半屏 ctrl+u 向上翻半屏 六.删除字符 x 删除光标所在的单词 #x 删除光标处向后#个字符 七.删除命令

Razor引擎常规用法

1.隐匿代码表达式 例: @model.name 会将表达式的值计算并写入到响应中,输入时采用html编码方式 2.显示表达式 例:@(model.name)会将输入@model.name字符串 3.无编码表达式 明确表渲染不应该采用html编码方式 例:@Html.Raw(model.name),会把model.name值计算原值输入,不经过Html编码处理. 4.@{代码块}可以在代码块中写C#代码,并可以在view使用 例:@{ var objname="mike"; var a

核心动画(Core Animation)简介及常规用法

Core Animation是一组非常强大的动画处理API,使用它能做出非常炫丽的动画效果,而且往往是事半功倍,使用它需要先添加QuartzCore.framework和引入对应的框架<QuartzCore/QuartzCore.h> 开发步骤: 初始化一个动画对象(CAAnimation)并设置一些动画相关属性. 添加动画对象到层(CALayer)中,开始执行动画. CALayer中很多属性都可以通过CAAnimation实现动画效果,包括:opacity.position.transfor

cpio命令常规用法介绍

cpio是用来建立.还原备份档的工具程序,它可以加入.解开cpio或tar备份档内的文件. 解压cpio文件 cpio -idmv < filename.cpio 解压img文件 cpio -idmv < filename.img 备份还原 备份:cpio -covB > [file|device] 将数据备份到文件或设备上 还原:cpio -icduv < [file|device} 将数据还原到系统中 常用参数 -B:让预设的blocks可以增加到5120bytes,默认是51

iOS-Swift-String(字符串常规用法)

// //  ViewController.swift //  Swift-String // //  Created by luorende on 16/9/10. //  Copyright © 2016年 luorende. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do

Java——Collection集合的常规用法

Collection 接口是 List .Set 和 Queue 接口的父接口,该接口定义的方法即可用于操作 Set 集合,也可用于操作 List 和Queue 集合. Collection 接口里定义了如下操作集合元素的方法. /** * boolean add(Object o): 该方法用于向集合里添加一个元素.如果集合对象被添加操作改变了,则返回 true * * boolean addAll(Collection c):该方法把集合c里的所有元素添加到指定集合里.如果集合对象被添加操作

scss常规用法

保持sass条理性和可读性的最基本的三个方法:嵌套.导入和注释. 一般情况下,你反复声明一个变量,只有最后一处声明有效且它会覆盖前边的值. $link-color: blue; $link-color: red; a { color: $link-color; } 最终编译成为红色 --------------------------------- & 在编译时将被替换为父选择符,如果你有一个深层嵌套的规则,父选择符也会在 & 被替换之前被完整的解析. #main { color: bla