iT邦幫忙

第 12 屆 iThome 鐵人賽

DAY 28
0
Modern Web

Vue菜鳥的自我學習days系列 第 28

28. Vuex State

Vuex使用单一状态树,用一个对象就包含了全部的应用层级状态。这也意味着,每个应用将只包含一个 store 实例

import Vue from 'vue';
import Vuex from 'vuex';

Vue.use(Vuex)

const app = new Vue({
  el: '#app',
  // 把 store 对象提供给 “store” 选项,这可以把 store 的实例注入所有的子组件
  store,
  components: { Counter },
  template: `
    <div class="app">
      <counter></counter>
    </div>
  `
})
// component
const Counter = {
  template: `<div>{{ count }}</div>`,
  computed: {
    count () {
      return this.$store.state.count
    }
  }
}

mapState 辅助函数
当一个组件需要获取多个状态的时候,将这些状态都声明为计算属性会有些重复和冗余。为了解决这个问题,我们可以使用mapState辅助函数帮助我们生成computed属性

import { mapState } from 'vuex'

export default {
computed: mapState([
  // 映射 this.count 为 store.state.count
  'count'
])
}

上一篇
27.Copmuted vs Watcher
下一篇
29.Getter and Mutation
系列文
Vue菜鳥的自我學習days39
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言