什么是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)