首页 > 其他分享 >Vuex 详解

Vuex 详解

时间:2022-12-14 17:01:12浏览次数:48  
标签:default state 详解 export import wheels Vuex store

state:

import { Module, VuexModule } from 'vuex-module-decorators'
 
@Module
export default class Vehicle extends VuexModule {
  wheels = 2
}
 
等同于下面的代码
 
export default {
  state: { wheels: 2 }
}

getter:

import { Module, VuexModule } from 'vuex-module-decorators'
 
@Module
export default class Vehicle extends VuexModule {
  wheels = 2
  get axles() {
    return this.wheels / 2
  }
}
 
等同于下面的代码
 
export default {
  state: { wheels: 2 },
  getters: {
    axles: (state) => state.wheels / 2
  }
}

@ Mutations:

import { Module, VuexModule, Mutation } from 'vuex-module-decorators'
 
@Module
export default class Vehicle extends VuexModule {
  wheels = 2
 
  @Mutation
  puncture(n: number) {
    this.wheels = this.wheels - n
  }
}
 
等同于下面的代码
 
export default {
  state: { wheels: 2 },
  mutations: {
    puncture: (state, payload) => {
      state.wheels = state.wheels - payload
    }
  }
}

@Action:

import { Module, VuexModule, Mutation, Action } from 'vuex-module-decorators'
import { get } from 'request'
 
@Module
export default class Vehicle extends VuexModule {
  wheels = 2
 
  @Mutation
  addWheel(n: number) {
    this.wheels = this.wheels + n
  }
 
  @Action
  async fetchNewWheels(wheelStore: string) {
    const wheels = await get(wheelStore)
    this.context.commit('addWheel', wheels)
  }
}
 
等同于下面的代码
 
const request = require('request')
export default {
  state: { wheels: 2 },
  mutations: {
    addWheel: (state, payload) => {
      state.wheels = state.wheels + payload
    }
  },
  actions: {
    fetchNewWheels: async (context, payload) => {
      const wheels = await request.get(payload)
      context.commit('addWheel', wheels)
    }
  }
}

@MutationAction:

export default class PassengerStore extends VuexModule {
  public username = '';
  public password = '';
 
  //'username'和'password'被返回的对象替换,
  //格式必须为`{username:...,password:...}` 
  @MutationAction({ mutate: ['username', 'password'] })
  async setPassenger(name: string) {
    const response: any = await request(name); // 接口返回 [{name:'张三',password:'123456'}]
    // 此处返回值必须和上面mutate后面的名称保持一致;
    return {
      username: response[0].name,
      password: response[0].password,
    };
  }
}
 
 
// index.vue中使用
<template>
    <div class="">
        用户名:{{PassengerStoreModule.username}}<br/>
        密码:{{PassengerStoreModule.password}}<br/>
        <button @click="getPassenger()">getPassenger</button>
    </div>
</template>
 
...
@Component
export default class IndexPage extends Vue {
    private PassengerStoreModule: any = PassengerStoreModule;
 
    getPassenger() {
        PassengerStoreModule.setPassenger('西施');
    }
}
 
// 运行过后,点击getPassenger按钮,用户名和密码会发生变化哦

@ 动态模块

动态模块:使用getModule获取数据,页面调用的时候,store.state里面才会显示改模块的信息
非动态模块:页面初始的时候,手动添加到new Vuex.Store({ modules: { user: PassengerStore } }),页面刷新state里面可以直接看到当前模块的变量以及方法。

我们将上面的passenger.ts改写才非动态模块

import {Module,VuexModule,Mutation,Action,getModule,} from 'vuex-module-decorators';
// import store from '@/store'; // 去掉store
 
type User = { username: string; password: string; }
 
@Module({name: 'user', namespaced: true,})
export default class PassengerStore extends VuexModule {
  // ...同上方案例一模一样
}
 
// 因为getModule是要对应store的.上面去掉了store,所以也要去掉 getModule,
// export const PassengerStoreModule = getModule(PassengerStore); 
 
// store/index.ts
import Vue from 'vue';
import Vuex from 'vuex';
import PassengerStore from './modules/passenger';
 
Vue.use(Vuex);
export default new Vuex.Store({
    modules: {
        user: PassengerStore
    },
});
 
//index.vue 使用
import PassengerStore from '@/store/modules/passenger';
import { getModule } from 'vuex-module-decorators';
 
...
created() {
  const PassengerStoreModule = getModule(PassengerStore, this.$store);
 
  console.log(PassengerStoreModule.loginInfo);
  PassengerStoreModule.getZhangsan();
  PassengerStoreModule.getLisi();
  console.log(PassengerStoreModule.userNumber);
  }
...

再试运行,发现跟之前的结果没差别.

命名空间

const moduleA1 = {
    namespaced: true,
    ...
};
const moduleA = {
    namespaced: true,
    modules: {
        a1: moduleA1,
    },
};
const moduleB = {
    // no namespaced
    ...
  };
export default new Vuex.Store({
    ...
    modules: {
        a: moduleA,
        b: moduleB,
    },
});

上面的例子,store包含了两个模块,a和b,a模块里面包含了a1,
打个比方a,a1和b的actions里面分别有个getMsgA(),getMsgB(),getMsgA1()方法,
在页面上用this.$store.dispatch调用这些方法.
a和a1都有命名空间,所以
this.$store.dispatch('a/getMsgA');
this.$store.dispatch('a/a1/getMsgA1');
由于b没有命名空间,所以this.$store.dispatch('b/getMsgB');是会报错的.

那么如果再a1里面如果查看root的state呢,vux提供了rootState, rootGetters.

actions: {
      someAction ({ dispatch, commit, getters, rootGetters }) {
        getters.someGetter // -> 'a/someGetter'
        rootGetters.someGetter // -> 'someGetter'
 
        dispatch('someOtherAction') // -> 'a/someOtherAction'
        dispatch('someOtherAction', null, { root: true }) // -> 'someOtherAction'
 
        commit('someMutation') // -> 'a/someMutation'
        commit('someMutation', null, { root: true }) // -> 'someMutation'
      }

标签:default,state,详解,export,import,wheels,Vuex,store
From: https://www.cnblogs.com/zhengzhijian/p/16982643.html

相关文章

  • Java继承详解
    继承的定义、功能及要求定义:class子类extends父类{}通常也称子类为派生类、父类为超类。功能: 继承的主要目的是使子类可以重用父类的结构,也可以根据子类功能的需......
  • 详解视频中动作识别模型与代码实践
    摘要:本案例将为大家介绍视频动作识别领域的经典模型并进行代码实践。本文分享自华为云社区《视频动作识别》,作者:HWCloudAI。实验目标通过本案例的学习:掌握C3D模型训......
  • JavaScript学习--Item29 DOM基础详解
    看完JavaScript高级程序设计,整理了一下里面的DOM这一块的知识点,比较多,比较碎!DOM在整个页面的地位如图:DOM(文档对象模型)是针对HTML和XML文档的一个API(应用程序编程接口)。DOM......
  • JavaScript的数据类型详解
    数据类型JavaScript中有5种简单数据类型(也称为基本数据类型):Undefined、Null、Boolean、Number和String。还有1种复杂数据类型——Object,Object本质上是由一组无序的名值对......
  • Go语言超全详解(入门级)
    Go语言超全详解(入门级)1.Go语言的出现在具体学习go语言的基础语法之前,我们来了解一下go语言出现的时机及其特点。Go语言最初由Google公司的RobertGriesemer、KenTho......
  • Python时间处理常用模块及用法详解!
    Python中最常用的三个处理时间的模块为:time模块、datetime模块和calendar模块,本文为大家详细介绍一下这三个时间处理模块以及它们的基础用法,希望对你们有帮助。1.t......
  • vuex的使用-简单存储
    在写新项目的时候,用input写了个搜索框,搜索之后获取到点击的数据,要将数据在tab中渲染出来,我思前想后,还是觉得vuex是最好的解决办法,记录一下vuex的基本用法首先是在store文......
  • luabind-0.9.1在windows、linux下的使用详解及示例
    一.下载  1. 本篇博客使用的版本为luabind-0.9.1二.编译  1.luabind-0.9.1在window 三.示例代码下载:  1.windows下示例代码下载地址(环境是win7,VS2008,已......
  • jsoncpp在linux和windows下的编译及使用详解
    一:摘要1.JSON是一种轻量级的数据传输格式,全称为:JavaScriptObjectNotation,官方网址:​​​http://www.json.org/json-zh.html​​​3.JSONCPP是......
  • 爆火出圈的人工智能ChatGPT注册使用详解
    .背景最近几天互联网刮起了一阵ChatGPT风,起因是人工智能研究实验室OpenAI在2022年11月30日发布的全新聊天机器人模型——ChatGPT就连联合创始人钢铁侠马斯克也在感叹:......