• 05 Vue进阶 Vuex多模块使用、Vuex 插件、 subscribe订阅等


    一.Vuex基础使用

    文件目录如下:

    0.创建Vuex 实例 

    定义Vuex实例

    1. /*
    2. * @Description:
    3. * @Version: 2.0
    4. * @Autor: Cookie
    5. * @Date: 2022-06-30 14:50:11
    6. * @LastEditors: Zhang
    7. * @LastEditTime: 2022-07-01 09:53:13
    8. */
    9. // Vuex数据单向流,数据规范性
    10. import Vuex from 'vuex'
    11. import defaultState from './state/state'
    12. import mutations from './mutations/mutaions'
    13. import getters from './getters/getters'
    14. import actions from './actions/actions'
    15. // import Vue from 'vue'
    16. // Vue.use(Vuex)
    17. // const store = new Vuex.Store({
    18. // state: {
    19. // count: 0
    20. // },
    21. // mutations: {
    22. // updateCount(state, num) {
    23. // state.count = num
    24. // }
    25. // }
    26. // })
    27. // export default store
    28. const isDev = process.env.NODE_ENV === 'development'
    29. export default () => {
    30. return new Vuex.Store({
    31. strict: isDev, //this.$store.state.count = 99; 开发环境限制这样的写法,规范团队
    32. state: defaultState, //全局模块
    33. mutations,
    34. getters,
    35. actions,
    36. })
    37. }

    创建Vuex实例

    1. /*
    2. * @Description:
    3. * @Version: 2.0
    4. * @Autor: Cookie
    5. * @Date: 2022-04-19 09:36:46
    6. * @LastEditors: Zhang
    7. * @LastEditTime: 2022-07-01 09:54:26
    8. */
    9. // The Vue build version to load with the `import` command
    10. // (runtime-only or standalone) has been set in webpack.base.conf with an alias.
    11. import Vue from 'vue'
    12. import Vuex from 'vuex'
    13. import App from './App'
    14. import router from './router'
    15. import createStore from '@/store/store'
    16. // import VueRouter from 'vue-router'
    17. // import createRouter from './router/router'
    18. // Vue.use(VueRouter)
    19. // const router = createRouter()
    20. Vue.use(Vuex)
    21. const store = createStore() //建议这样的方式创建,更容易维护
    22. Vue.config.productionTip = false
    23. /* eslint-disable no-new */
    24. new Vue({
    25. el: '#app',
    26. router,
    27. store,
    28. components: { App },
    29. template: '<App/>'
    30. })

    1.State

    state.js代码如下:

    1. export default {
    2. count: 222123,
    3. firstName: 'Cookie',
    4. lastName: 'Zhang'
    5. }

    调用state中的数据方式有二种

    1. <div>{{count}}</div>
    2. <div>{{counter}}</div>
    3. <script>
    4. import { mapState, mapGetters, mapActions, mapMutations } from "Vuex";
    5. computed: {
    6. count() {
    7. return this.$store.state.count; // 方式一
    8. },
    9. ...mapState({ // 方式二,最好的方式是使用对象形式
    10. // counter: "count" // 别名
    11. counter: state => state.count
    12. }),
    13. // ...mapState(["count"]),
    14. }
    15. </script>

    2.Getter

    getters代码如下:

    //getters类似组件中的coumpted,由于后端的数据获取过来我们需要再次组装,当然也可以再组件中写但是多个页面都需要使用就会重复写多次

    1. export default {
    2. fullName(state) {
    3. return `${state.firstName}---${state.lastName}`
    4. }
    5. }

     调用getter中的数据方式有二种

    1. <div>{{ fullName }}</div>
    2. <script>
    3. import { mapState, mapGetters, mapActions, mapMutations } from "Vuex";
    4. computed: {
    5. // fullName() { // 方式一
    6. // return this.$store.getters.fullName;
    7. // }
    8. ...mapGetters({ // 方式二,简写
    9. fullName: "fullName"
    10. }),
    11. </script>

    3.mutation

    mutation代码如下:

    mutation只能接受两个参数,第二个参数需封装成obj

    1. export default {
    2. updateCount(state, { num, num2 }) { //只能接受两个参数,第二个参数封装成obj
    3. console.log(num)
    4. console.log(num2);
    5. state.count = num
    6. }
    7. }

    调用mutation中的数据方式有二种 (mutation需要操作数据故需放在methods)

    4.Action

    Action.js代码如下:

    mutations同步的修改数据,actions异步的修改数据如

    1. // mutations同步的修改数据,actions异步的修改数据如
    2. export default {
    3. updateCountAsync(store, data) {
    4. setTimeout(() => {
    5. store.commit('updateCount', {
    6. num: data.num
    7. })
    8. }, data.time)
    9. }
    10. }

     调用Action中的数据方式有二种 (Action需要操作数据故需放在methods)

    1. <div>{{ counter }}</div>
    2. <script>
    3. import { mapState, mapGetters, mapActions, mapMutations } from "Vuex";
    4. mounted() {
    5. console.log(this.$store);
    6. this.$store.dispatch("updateCountAsync", { //方式一
    7. num: 5,
    8. time: 2000
    9. });
    10. this.updateCountAsync({ //方式二 建议使用
    11. num: 5,
    12. time: 2000
    13. });
    14. },
    15. methods: {
    16. ...mapActions(["updateCountAsync"]) // 引入
    17. },
    18. </script>

    二.Vuex多模块使用

    0.定义多模块加modules字段 

    定义模块a和b都添加上命名空间,namespaced: true,

    1. /*
    2. * @Description:
    3. * @Version: 2.0
    4. * @Autor: Cookie
    5. * @Date: 2022-06-30 14:50:11
    6. * @LastEditors: Zhang
    7. * @LastEditTime: 2022-07-01 09:53:13
    8. */
    9. import Vuex from 'vuex'
    10. import defaultState from './state/state'
    11. import mutations from './mutations/mutaions'
    12. import getters from './getters/getters'
    13. import actions from './actions/actions'
    14. // import Vue from 'vue'
    15. // Vue.use(Vuex)
    16. // const store = new Vuex.Store({
    17. // state: {
    18. // count: 0
    19. // },
    20. // mutations: {
    21. // updateCount(state, num) {
    22. // state.count = num
    23. // }
    24. // }
    25. // })
    26. // export default store
    27. const isDev = process.env.NODE_ENV === 'development'
    28. export default () => {
    29. const store = new Vuex.Store({ //hot moudle
    30. // return new Vuex.Store({
    31. strict: isDev, //this.$store.state.count = 99; 开发环境限制这样的写法,规范团队
    32. state: defaultState, //全局模块
    33. mutations,
    34. getters,
    35. actions,
    36. modules: {
    37. a: {
    38. namespaced: true, //命名空间,不设置在全局的mutations下,提升规范性
    39. state: {
    40. text: 1
    41. },
    42. mutations: {
    43. updateText(state, text) {
    44. console.log('a.stata', state)
    45. state.text = text
    46. }
    47. },
    48. getters: {
    49. // textPlus(state) { //只依赖a模块的值
    50. // return state.text + 1
    51. // }
    52. textPlus(state, getters, rootState) { //依赖全局模块的值 ,getters是获取全局的getters,rootState获取全局的state
    53. // return state.text + rootState.count // 获取顶层模块的
    54. return state.text + rootState.b.text //获取b模块的
    55. }
    56. },
    57. actions: {
    58. add({ state, commit, rootState }) {
    59. // commit('updateText', rootState.count) // commit默认获取本模块a 的mutations
    60. commit('updateCount', { num: 567 }, { root: true }) // 调用全局的mutations
    61. }
    62. }
    63. },
    64. b: {
    65. state: {
    66. text: 2
    67. },
    68. actions: {
    69. testAction({ state, commit, rootState }) {
    70. commit('a/updateText', 'test text', { root: true }) // 调用a的mutations
    71. }
    72. }
    73. }
    74. }
    75. })

    1.多模块a使用state

    1. <div>{{ texta }}</div>
    2. <script>
    3. import { mapState, mapGetters, mapActions, mapMutations } from "Vuex";
    4. computed: {
    5. texta() {
    6. return this.$store.state.a.text;
    7. }
    8. }
    9. </script>

     2.多模块a使用Getter

    1. <div>{{ textPlus }}</div>
    2. <script>
    3. import { mapState, mapGetters, mapActions, mapMutations } from "Vuex";
    4. computed: {
    5. // ...mapGetters(["fullName", "a/textPlus"]),
    6. ...mapGetters({
    7. fullName: "fullName"
    8. textPlus: "a/textPlus"
    9. }),
    10. }
    11. </script>

    3.多模块a使用mutation 和action

    1. <div>{{ texta }}</div>
    2. <script>
    3. import { mapState, mapGetters, mapActions, mapMutations } from "Vuex";
    4. mounted() {
    5. // 多模块Vuex
    6. this.updateText(123); // 添加了命名空间
    7. this["a/updateText"](123);
    8. this["a/add"]();
    9. },
    10. methods: {
    11. ...mapMutations(["a/updateText"])
    12. ...mapActions(["a/add"])
    13. },
    14. </script>

    三. Vuex 插件及api

    0.store.registerModule注册模块

    1.store.watch 监听state值变化

    2.store.subscribe监听muatation被调用

    3.store.subscribeAction监听action被调用

    1. /*
    2. * @Description:
    3. * @Version: 2.0
    4. * @Autor: Cookie
    5. * @Date: 2022-06-30 14:50:11
    6. * @LastEditors: Zhang
    7. * @LastEditTime: 2022-07-01 10:42:45
    8. */
    9. import Vuex from 'vuex'
    10. import defaultState from './state/state'
    11. import mutations from './mutations/mutaions'
    12. import getters from './getters/getters'
    13. import actions from './actions/actions'
    14. // import Vue from 'vue'
    15. // Vue.use(Vuex)
    16. // const store = new Vuex.Store({
    17. // state: {
    18. // count: 0
    19. // },
    20. // mutations: {
    21. // updateCount(state, num) {
    22. // state.count = num
    23. // }
    24. // }
    25. // })
    26. // export default store
    27. const isDev = process.env.NODE_ENV === 'development'
    28. export default () => {
    29. const store = new Vuex.Store({ //hot moudle
    30. // return new Vuex.Store({
    31. strict: isDev, //this.$store.state.count = 99; 开发环境限制这样的写法,规范团队
    32. state: defaultState, //全局模块
    33. mutations,
    34. getters,
    35. actions,
    36. plugins: [
    37. (store) => {
    38. console.log('my store plugin')
    39. store.registerModule('c', { //异步加载的时候才需要用到模块c,此时才需注册模块C
    40. state: {
    41. text: 31231
    42. }
    43. })
    44. store.watch((state) => state.count + 999, (newCount) => {
    45. console.log('new count watched:', newCount) //new count watched: 1000 ,count值发生改变会触发这个watch
    46. })
    47. store.subscribe((mutation, state) => { //用于Vuex插件中
    48. console.log(mutation.type) //updateCount 监听到mutation中被调用的方法
    49. console.log(mutation.payload) // {num: 1, num2: 2} 被传入的值
    50. })
    51. store.subscribeAction((action, state) => {
    52. console.log(action.type) //updateCountAsync 监听到Action中被调用的方法
    53. console.log(action.payload) // {num: 5}
    54. console.log(state)
    55. })
    56. }
    57. ]
    58. })
    59. return store
    60. }
    61. // Vuex数据单向流,数据规范性

    四. Vuex热更替(保持状态)

    1. /*
    2. * @Description:
    3. * @Version: 2.0
    4. * @Autor: Cookie
    5. * @Date: 2022-06-30 14:50:11
    6. * @LastEditors: Zhang
    7. * @LastEditTime: 2022-07-01 10:42:45
    8. */
    9. import Vuex from 'vuex'
    10. import defaultState from './state/state'
    11. import mutations from './mutations/mutaions'
    12. import getters from './getters/getters'
    13. import actions from './actions/actions'
    14. // import Vue from 'vue'
    15. // Vue.use(Vuex)
    16. // const store = new Vuex.Store({
    17. // state: {
    18. // count: 0
    19. // },
    20. // mutations: {
    21. // updateCount(state, num) {
    22. // state.count = num
    23. // }
    24. // }
    25. // })
    26. // export default store
    27. const isDev = process.env.NODE_ENV === 'development'
    28. export default () => {
    29. const store = new Vuex.Store({ //hot moudle
    30. // return new Vuex.Store({
    31. strict: isDev, //this.$store.state.count = 99; 开发环境限制这样的写法,规范团队
    32. state: defaultState, //全局模块
    33. mutations,
    34. getters,
    35. actions,
    36. plugins: [
    37. (store) => {
    38. console.log('my store plugin')
    39. store.subscribeAction((action, state) => {
    40. console.log(action.type) //updateCountAsync 监听到Action中被调用的方法
    41. console.log(action.payload) // {num: 5}
    42. console.log(state)
    43. })
    44. }
    45. ],
    46. })
    47. // Vuex 热更替
    48. if (module.hot) {
    49. module.hot.accept([
    50. './state/state',
    51. './mutations/mutaions',
    52. './actions/actions',
    53. './getters/getters'
    54. ], () => {
    55. const newState = require('./state/state').default
    56. const newMutations = require('./mutations/mutaions').default
    57. const newActions = require('./actions/actions').default
    58. const newGetters = require('./getters/getters').default
    59. store.hotUpdate({
    60. state: newState,
    61. mutations: newMutations,
    62. getters: newGetters,
    63. actions: newActions
    64. })
    65. })
    66. }
    67. return store
    68. }
    69. // Vuex数据单向流,数据规范性

  • 相关阅读:
    学习杂记1
    boltdb 原理
    Linux运行jmeter报错java.sql.SQLException:Cannot create PoolableConnectionFactory
    数据隐私重塑:Web3时代的隐私保护创新
    SSM基于WEB的房屋出租管理系统 毕业设计-附源码261620
    用声明式宏解析 Rust 语法
    游戏建模‖那些你找工作时不明白的事
    Hive:BUG记录,错误使用动态分区导致的插入失败
    某医疗机构:建立S-SDLC安全开发流程,保障医疗前沿科技应用高质量发展
    一、基本数据类型(数组)
  • 原文地址:https://blog.csdn.net/qq_37550440/article/details/125553447