VUEX博客

什么是vuex?

vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化。

vuex好处:

集中存储管理程序组件的状态,避免了组件通信的麻烦

场景:适用于中大型的单页面应用

vuex的运行机制:

在组件中通过this.$store.dispatch来调用actions中的方法,在action中通过commit来调用mutations中的方法,在mutations的方法中操作state中的数据,数据只要更新就会立即响应到组件上

vuex的使用

首先下载 vuex

cnpm install vuex --save

在src目录中,新建一个store的文件夹来存放index.js

import Vue from "vue";

import vuex from "vuex";

Vue.use(vuex);

var store=new vuex.Store({

    state:{
    //    变量
    },
    mutations:{
    //    方法
    },
    getters:{
    //    计算
    },
    actions:{
    //    异步
    }
    })
    export default store

在main.js中引入store

  import Vue from 'vue'
    import App from './App'
    import router from './router'
    import '@vant/touch-emulator';//--- rem ---
    import "./rem"
    import store from "./store/index"//store
    //引入vant开始
    import Vant from 'vant';
    import 'vant/lib/index.css';
    //引入vant结束
    Vue.config.productionTip = false
    Vue.use(Vant);//--- Vant ---
    /* eslint-disable no-new */
    new Vue({
      el: '#app',
      router,
      store,//store    //引入store文件
      components: { App },
      template: '<App/>'
    })

vuex核心概念

state 仓库 在组件中this.$store.state.参数名

mutations 直接操作state中的数据的方法 在组件中调用 this.$stote.commit(“方法名”,参数列表)

getter 类似于计算属性 来对state中的数据进行加工 在组件调用 this.$store.getters.方法名

actions 实现异步操作数据 在actions中调用mutations的方法 在组件中调用 this.$store.dispatch(“方法名”)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值