- vuex 的使用场景: 例如:几个不相关的组件想要共享一个数据的状态 -> Vuex 官方文档的说话是当遇到 ·多个组件共享状态时·可以用到Vuex
-
来自官方文档的图片.png
- state 可以理解为是所有组建想要共享的数据
- mutations 是定义改变 state 的数据
- actions 是什么时候改变 state 的数据 -> 提交 commit
- 总结就是: 数据放在 state 里,怎么改变通过 mutations 进行改变,什么时候改变的行为都放在 actions
- Vue 模板 render 数据 (state)
- components 接受用户的交互,触发 actions ,通过 dispatch 触发
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const state = {
count: 1
}
const mutations = {
increment (state) {
state.count += 1
},
decrement (state) {
state.count -= 1
}
}
const actions = {
increment: ({commit}) => {
commit('increment')
},
decrement: ({commit}) => {
commit('decrement')
}
}
const store = new Vuex.Store({
state,
mutations,
actions
})
new Vue({
el: '#app',
render (h) {
return h(App)
},
store
})
<template>
<div id="app">
<img src="./assets/logo.png">
<div>{{ $store.state.count }}</div>
<button @click="increment">增加</button>
<button @click="decrement">减少</button>
</div>
</template>
<script>
import { mapActions } from 'vuex'
export default {
name: 'App',
data () {
return {
msg: 'hello world'
}
},
methods: mapActions([
'increment',
'decrement'
])
}
</script>
<style>
#app {
font-family: 'Avenir', Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
</style>
网友评论