一、Vuex是什么
Vuex是实现组件全局状态(数据)管理的一种机制,可以方便的实现组件之间数据的共享。
优点:
能够在Vuex中集中管理共享的数居,易于开发和后期维护
能够高效地实现组件之间的数据共享,提高开发效率
存储在vuex中的数据都是响应式的,能够实时保持数据与页面的同步
什么样的数据适合存储到Vuex中:
一般情况下,只有组件之间共享的数据,才有必要存储到vuex中;对于组件中的私有数据,依旧存储在组件自身的data中即可。
main.js
import Vue from 'vue'
import App from './App.vue'
import store from './store'
Vue.config.productionTip = false
new Vue({
store,
render: h => h(App)
}).$mount('#app')
store / index.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
},
mutations: {
},
actions: {
},
modules: {
}
})
二、State 数据源
State提供唯一的公共数据源,所有共享的数据都要统一放到 Store的 State I中进行存储。
//创建store数据源,提供唯一公共数据
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
count: 0
},
mutations: {
},
actions: {
},
modules: {
}
})
2.1 通过 this.$store.state.全局数据名称 访问
this.$store.state.全局数据名称
由于在模板字符串中,是不需要写this的,所以直接写this后边的。
<h3>当前最新的count值为