Vuex

Vuexless

先來看一下,沒有Vuex時,寫一個例子。

HTML
< div id="app">
  < counter :num="count">< /counter>
  < p>
    < button @click="increment">+< /button>
    < button @click="decrement">-< /button>
  < /p>
< /div>
javascript
const Counter = {
    template: `< div>{{ num }}< /div>`,
  props: ['num'],
}

const app = new Vue({
  el: '#app',
  data: {
    count: 0
  },
  components: {
    'counter': Counter
  },
  methods: {
    increment () {
      this.count++
    },
    decrement () {
      this.count--
    }
  }
})
Result

Vue 的 State

state into components

要先將 Vuex 宣告出來,並且將 data 搬進 state

JavaScript

Vue裡的data

const app = new Vue({
  data: {
    count: 0
  },
  //...
}

搬到Vuex.Store變成

const store = new Vuex.Store({
  state: {
    count: 0
  }
})

再改寫Components裡,更新內容的機制

componentsprops

const Counter = {
    //...
    props: ['num'],
  }

改成 componentscomputed

const Counter = {
    //...
    computed: {
      count() {
        return this.$store.state.count
      }
    }
  }

Vue的要加上「註冊使用Vuex」

const app = new Vue({
  //...
  state,
  //...
}

Componentstemplate的prop傳值機制刪掉

HTML

原本這樣

< counter :num="count">< /counter>

改成這樣

< counter>< /counter>
改好全部長這樣
< div id="app">
  < counter>< /counter>
  < p>
    < button @click="increment">+< /button>
    < button @click="decrement">-< /button>
  < /p>
< /div>
const store = new Vuex.Store({
  state: {
    count: 0
  }
})

const Counter = {
  template: `< div>{{ count }}< /div>`,
  computed: {
    count() {
      return this.$store.state.count
    }
  }
}

const app = new Vue({
  el: '#app',
  store,
  components: {
    'counter': Counter
  },
  methods: {
    increment () {
      store.state.count++
    },
    decrement () {
      store.state.count--
    }
  }
})

mapState

這是一個,可以透過Vue實體,存取到Vuexstate的一種機制

javascript

只要加上這一行

var app = new Vue({
    data: {
      countA: 123 //just for local computed
    },
    computed: {
      // just local computed
      countAplus () {
        return this.countA + 1
      },
      //mapState
      ...Vuex.mapState({
        count: state => state.count,
      })
    },
    //...
  })

不過,它還有更有意思的用法,就是可以結合 local data 的methods

var app = new Vue({
    computed: {
      // local computed
      ...Vuex.mapState({
        count: state => state.count + this.countA,
      })
    },
    //...
  })

mapGetter

就是一個被共用的computed