VVuex的基本介绍、状态管理、单界面的状态管理、多状态管理及使用案例
1、VueX是做什么的?
管理所有组件的状态
2、用VueX来管理什么状态?
用户登录状态
3、单界面的状态管理
<template>
<div id="app">
<h2>{
{
message}}</h2>
<h2>{
{
counter}}</h2>
<button @click="counter--">-</button>
<button @click="counter++">+</button>
</div>
</template>
<script>
export default {
name: 'App',
data(){
return{
message: '我是APP页面的组件',
counter:0
}
}
}
</script>
<style>
</style>
如下图所示,点击按钮–>触发状态–>页面改变
4、多页面状态管理
多页面状态管理官方图例:
5、多页状态管理案例
1、创建store对象
src/store/index.js
import Vue from 'vue';
import Vuex from 'vuex'
//1、安装插件
Vue.use(Vuex)
// 2、创建对象
const store = new Vuex.Store({
state:{
counter:0
},
mutations: {
increment(state){
this.state.counter++
},
decrement(state){
this.state.counter--
}
}
})
// 3、导出store对象
export default store
2、挂载到Vue实例中去:
src/main.js
import Vue from 'vue'
import App from './App'
import store from './store'
Vue.config.productionTip = false
/* eslint-disable no-new */
new Vue({
el: '#app',
store,
render: h => h(App)
})
3、使用Vuex的counter
src/APP.vue
<template>
<div id="app">
<h2>{
{
message}}</h2>
<h2>{
{
$store.state.counter}}</h2>
<button @click="subtraction">-</button>
<button @click="addition">+</button>
<hello-vuex></hello-vuex>
</div>
</template>
<script>
import HelloVuex from './components/HelloVuex'
export default {
name: 'App',
components:{
HelloVuex
},
data(){
return{
message: '我是APP页面的组件'
}
},
methods:{
addition:function(){
this.$store.commit('increment')
},
subtraction:function(){
this.$store.commit('decrement')
}
}
}
</script>
<style>
</style>