一、概念
vuex:状态(共享变量–>其他组件的功能)管理组件
state:放数据
views:显示数据,是.vue组件
action:更改数据
二、开发状态管理功能:
0 --> + -->1
1.安装vuex依赖
npm i --save vuex
写state:对象是常量,值是变量,指向地址不能变,指向空间的值是可变的。
根据基础知识,程序在启动时,会自动触发src/main.js,
因此,思路:可以将store.js暴露的多个对象封装到main.js中,
src/main.js–>store–>App.vue
程序的启动顺序:先main.js(store)–>App.vue,因此在使用App.vue时已经加载过了store,App.vue可以直接使用store,使用方式:$store
2.执行过程:store.js—>main.js–>组件(编写代码顺序)
2.1 store/index.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
//共享变量
const state={
count:0
}
//直接操作共享变量的对象
const mutations={
mulincrease(state){
//自增1
state.count++;
}
}
//操作mulations的对象
const actions={
//自增传入对象,然后调用
actincrease({commit}){//传多个对象用{}
commit('mulincrease');
}
}
//将store.js中的对象暴露外界,用于其他组件的共享
export default new Vuex.Store({
state,
mutations,
actions
})
2.2 main.js
import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
Vue.config.productionTip = false
new Vue({
router,
store,//注入store对象,其中包含了state,mutations,actions
render: function (h) { return h(App) }
}).$mount('#app')
2.3 App.vue
<template>
<div id="app">
{{$store.state.count}}
<button @click="countinc">+</button>
</div>
</template>
<script>
export default {
methods:{
countinc(){
//store是一个全局对象,在方法内要用this来拿
this.$store.dispatch('actincrease')
}
}
}
</script>
<style lang="scss">
</style>
2.4 结果: