Vuex的基本介绍、状态管理、单界面的状态管理、多状态管理及使用案例

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>

猜你喜欢

转载自blog.csdn.net/qq_46112274/article/details/123405017
今日推荐