在store/index.js
初始化vuex
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const store = new Vuex.Store({
state: {
count: 0
},
mutations: {
increment (state) {
state.count++
}
}
})
在main.js
导入vuex
import Vue from 'vue'
import App from './App.vue'
import store from "@/store";
Vue.config.productionTip = false
new Vue({
render: h => h(App),
store: store,
}).$mount('#app')
在组件中使用
<template>
<div id="app">
{{ this.$store.state.count }}
<button @click="add">加一</button>
</div>
</template>
<script>
export default {
name: 'App',
methods: {
add() {
this.$store.commit("increment")
}
}
}
</script>
简化this.$store.state
<template>
<div id="app">
{{ count }}
<button @click="add">加一</button>
</div>
</template>
<script>
import {mapState} from 'vuex';
export default {
name: 'App',
computed: {
...mapState([
// 将this.$store.state.count 映射为 count
'count',
])
},
}
</script>
对于一个列表,我们可以只想要获取其中done属性为true的元素,因此我们需要设置getter
,通过mapGetter
简化getter
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const store = new Vuex.Store({
state: {
todos: [
{id: 1, text: '...', done: true},
{id: 2, text: '...', done: false}
]
},
getters: {
doneTodos: state => {
return state.todos.filter(todo => todo.done)
}
},
})
export default store
<template>
<div id="app">
{{ doneTodos }}
<button @click="add">加一</button>
</div>
</template>
<script>
import {mapState, mapGetters} from 'vuex';
export default {
name: 'App',
computed: {
...mapGetters([
// 将this.$store.getter.doneTodos 映射为 doneTodos
'doneTodos',
])
},
}
</script>
简化Mutations
import { mapMutations } from 'vuex'
methods: {
...mapMutations([
// 将 `this.increment()` 映射为 `this.$store.commit('increment')`
'increment',
// `mapMutations` 也支持载荷:
'incrementBy' // 将 `this.incrementBy(amount)` 映射为 `this.$store.commit('incrementBy', amount)`
]),
}