Basic introduction of VVuex, state management, single-interface state management, multi-state management and use cases
1. What does VueX do?
Manage the state of all components
2. What state is managed with VueX?
User login status
3. Single interface status management
<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>
As shown in the figure below, click the button -> trigger state -> page change
4. Multi-page status management
Official legend of multi-page status management:
5. Multi-page status management case
1. Create a store object
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. Mount it to the Vue instance:
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. Use Vuex's 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>