Vuex

了解Vuex,一个专为Vue.js应用程序设计的状态管理模式。通过集中式存储管理组件状态,Vuex提供了一种可预测的方式使状态发生变化,适用于中大型单页面应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

vuex的使用 :

首先下载 vuex

1、cnpm install vuex --save 

在src目录中,新建一个store的文件夹来存放index.js
//导入vue和vuex的包 在导出store

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

// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
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
  components: { App },
  template: '<App/>'
})

看注释为 //store 的配置

vuex核心概念
state 仓库 在组件中this.$store.state.参数名
mutations 直接操作state中的数据的方法 在组件中调this.$stote.commit("方法名",参数列表)
getter 类似于计算属性 来对state中的数据进行加工 在组件调用 this.$store.getters.方法名
actions 实现异步操作数据 在actions中调用mutations的方法 在组件中调用 this.$store.dispatch("方法名")

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

vuex好处:
集中存储管理程序组件的状态,避免了组件通信的麻烦
场景:适用于中大型的单页面应用
(不是说所有的地方都要用到 vuex 如果说是父传子子传父的地方使用vuex反而麻烦,对于复杂的组件通信时在使用vuex)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值