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

https://ithelp.ithome.com.tw/upload/images/20211219/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参数传递放渲染处
https://ithelp.ithome.com.tw/upload/images/20211219/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
https://ithelp.ithome.com.tw/upload/images/20211219/20137684a1XJq2thcN.png

(5) modules

模组化
https://ithelp.ithome.com.tw/upload/images/20211219/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可做区隔


<<:  Rules Engine 规则引擎

>>:  D7. 学习基础C、C++语言

D23 - 用 Swift 和公开资讯,打造投资理财的 Apps { 台股成交量实作.3 }

在 KLineViewController 开出的 volumeDataSet 会在 parent ...

计算资源及资料的设定01

前面谈到,执行[Machine Learning]的工作,除了计算资源外,最重要的便是资料了。我们先...

ISO 27001 资讯安全管理系统 【解析】( 十三)

陆、第五章 领导统御 成功的ISMS是由上而下实行的,透过考虑利害关系者的要求及采取有效控制措施将营...

【30天Lua重拾笔记31】进阶议题: 记忆体回收&弱表

TL;DR: 不要去修改预设值,除非你知道在做什麽 Lua会自己做记忆体回收,绝大多数时候不必为记...

Day 20 - React.memo

如果有错误,欢迎留言指教~ Q_Q 没写完啦 子元件通常会接收父元件的 state 或 event...