先來看一下,沒有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
state into components
要先將 Vuex 宣告出來,並且將 data 搬進 state
JavaScriptVue
裡的data
const app = new Vue({
data: {
count: 0
},
//...
}
搬到Vuex.Store
變成
const store = new Vuex.Store({
state: {
count: 0
}
})
再改寫Components
裡,更新內容的機制
將 components
的props
const Counter = {
//...
props: ['num'],
}
改成 components
的computed
const Counter = {
//...
computed: {
count() {
return this.$store.state.count
}
}
}
Vue
的要加上「註冊使用Vuex」
const app = new Vue({
//...
state,
//...
}
Components
的template
的prop傳值機制刪掉
原本這樣
< 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--
}
}
})
這是一個,可以透過Vue
實體,存取到Vuex
的state
的一種機制
只要加上這一行
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,
})
},
//...
})
就是一個被共用的computed