我刚试过这个(出于好奇)。
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
<script src="https://unpkg.com/vue"></script>
<script src="https://unpkg.com/vuex"></script>
<script src="https://unpkg.com/immutable"></script>
</head>
<body>
<div id="app">
<button @click="increment">
+ (Increment)
</button>
{{ count }}
<button @click="decrement">
- (Decrement)
</button>
<hr>
<input v-model="count" placeholder="Change Value"/>
</div>
<script>
const { Store } = Vuex;
const { Map } = Immutable;
const immutableCount = Map({
value: 0
})
const countReducer = ({ state, type, value}) => {
const count = state.count;
let newCount;
switch(type) {
case 'INCREMENT':
newCount = count.update('value', x => x + 1);
break;
case 'DECREMENT':
newCount = count.update('value', x => x - 1);
break;
case 'SET_VALUE':
newCount = count.set('value', value);
break;
}
state.count = newCount;
}
const state = {
count: immutableCount
}
const mutations = {
INCREMENT(state) {
countReducer({
state,
type: 'INCREMENT'
})
},
DECREMENT(state) {
countReducer({
state,
type: 'DECREMENT'
})
},
SET_VALUE(state, value) {
countReducer({
state,
type: 'SET_VALUE',
value
})
}
}
const actions = {
increment({ commit }) {
commit('INCREMENT');
},
decrement({ commit }) {
commit('DECREMENT');
},
setValue({ commit }, value) {
commit('SET_VALUE', value);
}
}
const store = new Store({
state,
mutations,
actions
})
const dispatchers = {
increment() {
this.$store.dispatch('increment');
},
decrement() {
this.$store.dispatch('decrement');
},
setValue(value) {
this.$store.dispatch('setValue', value)
}
}
const count = {
get() {
return this.$store.state.count.get('value');
},
set(value) {
this.setValue(value ? value : 0)
}
}
const computed = {
count
}
const app = new Vue({
el: '#app',
computed,
methods: {
...dispatchers
},
store
})
</script>
</body>
</html>