vue2使用vueX

vueX简介

  vuex是程序开发过程中 集中状态管理模式,白话文:vueX用来管理所有组件共享的数据
  某一个数据在多个组件(视频组件、图片组件、订单组件等)中共享,可以使用vuex

 

核心概念: 

    基础使用:
      state:定义定义全局共享数据
      getters:获取state中的数据
      mutations:向state中设置新的数据/修改数据,是一个同步阻塞
    高级:
      actions:向state中设置新的数据/修改数据,是一个异步
      modules:将store提取出来,作为单独文件

 

vue2使用vueX步骤

  1、在src目录下创建store目录

  2、在store目录下创建index.js文件,用来书写vuex语法

  3、如下

import Vue from 'vue';
import Vuex from 'vuex';

// 让vue使用状态管理
Vue.use(Vuex);

// 暴露vueX对象
export default new Vuex.Store({

  // 定义共享数据,变量
  state: {
    count: 0
  },
  // 用来定义对共享数据进行修改的方法。修改数据,,是一个同步阻塞,方法名随便起
  mutations: {
    // 方法名随便起,参数state是定义中的变量,第一个变量必须是state,而且是默认的
    increment (state) {
      // 业务代码逻辑
      state.count++
    },
    // 两个参数
    increment(state,参数2){
      state.count+=参数2
    },

    //3个以上参数,可以定义对象n.m是指传参中的属性
    increment(state,obj){
      state.count+=obj.n+obj.m
    },

  },
  // vuex中计算属性,只能计算vuex中state中的属性
  getters:{
      // 方法名
      a(state){
        // 业务代码
      }
  },

  actions: {
    incrementAsync({ commit }) {
      setTimeout(() => {
        commit('increment');
      }, 1000); //定时任务,延时1秒
    },
  },

});

  4、在main.js中注册

// 引入vuex
import Vuex from 'vuex'
Vue.use(Vuex) // vue使用vuex状态管理
// 导入store
import store from './store'

new Vue({
  el: '#app',
  router,
  store, //添加到vue上
  components: { App },
  template: '<App/>'
})

  5、在组件中对数据的访问

  //操作state
  //访问数据
    使用方式一:(推荐使用)
      this.$store.state.变量名
    使用方式二:
      $store.state.变量名

  //操作mutations,是同步操作
  // 添加/修改数据(具体是看方法中业务逻辑)
    this.$store.commit('方法名')
    this.$store.commit('方法名',参数2)
    this.$store.commit('方法名',参数2,参数3...)
    this.$store.commit('方法名',{n:数据1,m:数据2})

  //操作getters
    $store.getters.方法名

  //Actions类似于Mutations,是异步操作
    $store.dispatch('方法名')

   6、案例

 <div style="color: #ff3366">{{this.$store.state.counter}}</div>

 

posted @ 2024-03-23 10:00  向大海  阅读(267)  评论(0编辑  收藏  举报