Day 18:产地直送,先拿再用-Vuex State、Getters

承上篇从 Actions 进展到 Mutations,接下来让 Mutations 将结果直接赋值给 State,继续接棒完成 Vuex 状态存取流程!

State 产地直送

  • 存取 state 只透过 mutations 和 getters:

    • 只有提交 mutation 才能改变 state,并且接收 mutation 直送的原始资料
    • 只有透过 getter 才能取得 state
  • 在被 mutation 改变之前,最好先设定预设值,完成初始化属性。

    state: {
        bookList: {},
    },
    
  • Vuex.Store 实例属性 store.state 只能读取 root state object
    若有模组化可进一步读取模组内的 state 状态

Getters 先拿再用

  • 只有透过 getter 才能取得 state,并依取用需求在 getter 中进行资料处理。

  • getter 作为 Store 的计算属性,回传值会随着依赖值发生改变才会被重新计算。

  • getter 函式第一个参数为 state,第二个参数为 getters(引用模组内的其他 getters)。

    getters: {
        bookList: (state) => state.bookList.list,
        bookUpdate: (state) => state.bookList.updatedAt,
    },
    

    若为模组化形式,则可再取用第三个参数 rootState 和第四个参数 rootGetters
    若只想取用第三个参数,前两个参数一样要设置,因为其判断参数是依照引用顺序。

    getters: {
        // 取用 root 的 state
        bookQuantity: (state, getters, rootState) 
    				=> rootState.quantity,
    
        // 取用另一个模组的 state
        discountBookList: (state, getters, rootState) 
    				=> rootState.anotherModule.list,
    },
    
  • Vuex.Store 实例属性 store.getters 只能读取所有注册的 getter object
    透过属性访问的 getter,会作为 Vue 响应式系统的一部份而被缓存(cached)。

    console.log(this.$store.getters);  // 显示注册的 bookList 和 bookUpdate
    console.log(this.$store.getters.bookUpdate);  // 1632672007
    

    store.getters

  • 透过方法访问的 getter,会在每次被访问时调用方法,而不会缓存结果。

    getters: {
      // ...
      getBookListByISBN: (state) => (ISBN) => {
        return state.books.find(book => book.ISBN === ISBN)
      }
    }
    
    store.getters.getBookListByISBN(9789867794529)
    // -> { ..., "name": "深入浅出设计模式", "ISBN": "9789867794529" }
    

补充:物件解构赋值范例

以我们最熟悉的 console 物件为例,其本身也包含许多方法。
console object

试着对 console 进行解构赋值。

const { log, warn } = { log: '[Function: log]', warn: '[Function: log]' }
console.log(log);

const { error } = console;
error('console.error');
console.error('error');
// error() = console.error()

console result
依此类推,希望有帮助到大家理解上篇 action 中的 context 物件解构,後续也会应用到 v-slot 上。

参考资料


<<:  [第18天]理财达人Mx. Ada-证券扣款帐户银行余额资讯

>>:  Day18 - 如何在页面中预先载入其他的页面 (prefetch)

Render Functions

今天要介绍的是Render Functions 先来看一段官网对render function的介绍...

Day 28 : C语言 - 如何解决用scanf连续输入时,程序会自动断行的问题?

如标题,scanf是一个「动态输入」的函数,你可以先宣告一个变数a,再用scanf输入,赋予它任意值...

第29天:解构语法、余集(...)

ES6开始支援解构语法,可以拆解某个资料结构,并指定给变数。 例如: let arr = [ 1, ...

Day 23: WAF web ACL、rules group建立

如何建立Web ACL? 1.找到WAF,按Create web ACL 2.输入名称、Cloudw...

【从零开始的Swift开发心路历程-Day14】打造自己的私房美食名单Part3(完)

昨天已经能让TableViewCell显示餐厅资料了 但....好像有点单调,让我们来加点餐厅的图片...