2020-07-13 23:23:17
vuex的概念:
vuex是全局状态管理工具(单向数据流), 是一个专为 Vue.js 应用程序开发的状态管理模式。主要用来解决组件之间的一个数据沟通问题,一般用于大型项目之间的一个数据传递(方便),小型项目一般不会用它,因为比较消耗性能.(偶和性,是个插件)
安装下载
搭建环境:
1.下载到生产环境:cnpm install vuex -S
2.下载完成后在src下新建一个store文件夹,文件夹下新建一个index.js文件
index.js
import Vue from 'vue' //引入vue
import Vuex from 'vuex' //引入vuex
// vue 去使用vuex
Vue.use(Vuex)
// 实例化
let store = new Vuex.Store({
state:{
count:100
},
mutations:{
},
getters:{
},
actions:{
},
})
export default store //导出
3.找到main.js
import store from './store'
new Vue({
el: '#app',
router,
store, //挂上
components: {
App },
template: '<App/>'
})
4.在任意组件中里打印this.$store.count,如果有count为100,则说明
vuex环境搭建没有问题。
核心:
核心就是 store(仓库):
state: vuex中的全局状态,在任何组件中都可以拿到
mutations: vuex中改变状态的方法集合
getters: vuex中的计算属性
actions: vuex中的异步方法## 标题
modules: vuex中的数据模块化
vuex中的getters:
1.相当于vue组件中的计算属性,在store下的indx.js中和state同级
getters:{
sum(state){
let sum=0;
state.arr.fprEach((item)=>{
sum+=item
})
return sum
}
}
//在组件中的计算安属性中
computed:{
sum(){
return this.$store.getters.sum
}
}
vuex中的actions工作流程;:
1.想要请求的数据,你可以写在actions里,在这里定义一个方法
actions:{
cnodeAjax(){
//同级的
axios.get("接口地址").then((res