vuex
初始化
- store/index.js
import Vuex from 'vuex';
import Vue from 'vue';
Vue.use(Vuex)
export default new Vuex.Store({
state:{
},
mutations:{
},
actions:{
},
getters:{
},
modules:{
}
})
- main.js
import store from './store/index.js'
Vue.prototype.$store = store;
vuex的模块
state:状态,存储数据
- state定义数据
state:{
gTitle:{
title:"你好Vuex",
color:"#f00",
fontSize:"24px",
backgroundColor:"#0f0"
},
joks:[],
},
- 在页面中使用:$store.state.gTitle.title
- 修改只能通过mutations
- 组件中简写
import {
mapState} from 'vuex'
computed:{
...mapState(["gTitle"])
}
mutations:修改数据的唯一方法
- 定义
//更改字体大小
setSize(state,data){
state.gTitle.fontSize = data + "px"
},
//更改背景颜色
setBackgroundColor(state,data){
state.gTitle.backgroundColor = data
},
setJok(state,data){
state.joks = data
}
- 页面中使用:this.$store.commit(“setSize”,e.detail.value)
- 简写
1、导入:import {mapMutations} from ‘vuex’
2、 methods:…mapMutations([“setFontSize”]),
3、 使用:this.setFontSize(100)
actions:异步api操作
- 定义
getJok(context,data){
uni.request({
url:"http://520mg.com/mi/list.php",
method:'GET',
data:data,
//axios get请求传参用params,post用data
//uni.request,get与post都用data
// content-type如果是application-json那么data是json
//如果是urlencoeded data就是url编码形式
success:res=> {
console.log("getJok",res)
context.commit("setJok",res.data.result)
}
})
}
-
页面中使用:this.$store.dispatch(“getJok”,{page:1})
-
简写:
1、导入:import {mapActions} from ‘vuex’
2、methods中计算:…mapActions([“getJok”]),
3、onLoad中使用:this.getJok() -
actions中的context
1、commit:执行mutations方法
2、dispatch:执行actions的方法
3、state:数据
4、getters:计算出来的是数据
getters:内部计算
- 定义
"totalLen":function(state){
var count = 0;
for(