Vuex ( 似Vue3 mitt )

1.Vuex通常在main.js内就被引入了(store),除map外无须另外引入

import { mapState, mapMutations } from "vuex";

2.store架构

import { createStore } from "vuex";
export default createStore({  // state 相当于data() 资料变数放这~  state: {    name: "茸茸鼠",    age: 15,  },  getters: {    // 似Vuex内的computed    // 仅能渲染,无法变更state  },  mutations: {    // mutations 方法 改变 state内资料  },  actions: {    // 1. actions似mutation但不能改变state    // 2. actions用于非同步(Axios)  },  modules: {    // 模组化 可以放state、getters、mutations、actions    // 似composition,整理用  },});

3.对照组 store vs. view > XXX.vue

state、getters、mutations、actions、modules皆有map
map功能:用[]装所有的该方法

(1) state:{}

似data(),存放要传递的资料

有...mapState(["name","age","price"]),

(2) getters:{}

似computed,监听并须return,不可改变State

a. 製作欲传递的资料,参数放functions()内传递
b. 于欲渲染叶面,渲染都要透过computed并须return
c. mapGatter 放将getters放于[]内,就无需写很多function

    ...mapGetters(      ["sellingPrice80Off","sellingPrice70Off"]      ),

等同

    sell80off(){      return this.$store.getters.sellingPrice80Off;    },    sell70off(){      return this.$store.getters.sellingPrice70Off;    },

d. 变更名称
e. ...必要,否则只放得下一个map

http://img2.58codes.com/2024/20137684Beb5icAN56.png

(3) mutations 

似方法可改变State

a. 渲染页製作仓库,先抓store内的state资料渲染在画面上
b. 触发方法,使渲染画面与store连接、传值达mitt效果
this.$store.commit("function名称", 传送的值)
c. store接收值,并改变store内的State
ifDrinkMilk(store的State, commit传过来的值)
State.yourCup = reciveCommit;
d. 渲染回页面
e. mapMutations参数传递放渲染处
http://img2.58codes.com/2024/20137684uC24OGoyya.png

(4) actions

跟 mutations 类似,但他不能直接操作state里的资料
执行非同步的任务,再将结果提交给mutations去更改state状态

actions 搭配 context(内建方法) 方法有2:commit、dispatch
a. context.commit("方法名称", "要传入的资料");
给mutations 

b. context.dispatch("方法名称", "要传入的资料");
给actions内

补充:
$store.commit
给mutations 

$store.dispatch
给actions内

结论commit给mutations、dispatch给actions
http://img2.58codes.com/2024/20137684a1XJq2thcN.png

(5) modules

模组化
http://img2.58codes.com/2024/20137684Ol8svyVQPE.png


4.rootstate

可以拿到根部、根元件的state与同层(隔壁的)state

    getRealAge(state, getters, rootState) {      return rootState.age;    },//根部export default createStore({  state: { name: "原stateName", age: 30, hhh:123 },  mutations: {},  actions: {},  modules: {    userA: moduleA,    userB: moduleB,  },});

5.namespaced

方法同名时,namespaced可做区隔


关于作者: 网站小编

码农网专注IT技术教程资源分享平台,学习资源下载网站,58码农网包含计算机技术、网站程序源码下载、编程技术论坛、互联网资源下载等产品服务,提供原创、优质、完整内容的专业码农交流分享平台。

热门文章