Vuex
介绍.
vuex用于组件之间没有直接关系的传值.
是一个专未vue.js应用程序开发的状态管理模式
.采用集中式存储
管理应用所有的组件状态,解决多组件数据通信
本质上和vue-router 一样是一个基于vue开发的插件.
主要用于大型项目..
1.手动创建脚手架
1.vue create 脚手架文件名
2.选择Manually手动
3.选择配置项
4.选择 版本2.x
5.选择N
6.选择less
7.标准严格模式
剩下的全部Enter.
创建完毕脚手架以后
9.下载对应插件
yarn add vuex
1,state(重要)
1.作用:
vuex用它来保存公共数据
2.定义公共数据
new Vuex.Store({
// state(){
// return{}
// }
state:{
class:'web67',
}
})
3.使用公共数据
在组件中使用 也就是在js代码中通过this.
this.$store.state.class
在模板中 也就是html里面使用
$store.state.class
2.mutations(重要)
1.作用
.能用它修改state中的数据.
修改state中的数据必须用到mutations.
2.定义语法格式
mutations:{
自定名:function(state,形参可选){
state.username.name = 形参
}
}
--------
3.使用定义的内容 通过时间触发
this.$store.commit('自定名',实参 给第二个参数.)
4.多个参数使用对象
mutations:{
自定名:function(state,{形参可选,形参2}){
state.username.name = 形参
state.username.name = 形参2
}
}
5.接收多个
this.$store.commit('自定名',{参数1,参数2,参数3})
3.getters 加工
1.定义
getters: {
sum(state) {
return state.books.reduce((item,obj)=>item+obj.price,0)
}
}
2.接收
<span>总金额:{{$store.getters.sum}}</span>
4.actions
定义
actions: {
AgetBooks({commit}) {
axios('https://www.fastmock.site/mock/37d3b9f13a48d528a9339fbed1b81bd5/book/api/books').then(res => {
commit('Newbooks',res.data.data)
})
}
}
在页面打开的时候调用
created(){
this.$store.dispatch('AgetBooks')
},
5.modules
按照模块根据不同的功能拆分
当创建基础的脚手架时.
1.下载vuex.
yarn add vuex
2.导入vuex.
import Vue from 'vue'
import Vuex from 'vuex'
3.注册
Vue.use(Vuex)
4.
const store = Vuex.Store({
state:{
},
mutations:{
},
getters:{
},
actions:{
}
})
5.暴露出去
export default store
6.在main.js中接收
import store from './router/index'
new Vue({
store,
render: h => h(App),
}).$mount('#app')