在上一篇文章介绍了uni-app的基本用法,本章介绍在uni-app中vuex、组件、api的用法。
一、如何使用vuex
1.1 初始化
在项目根目录下创建store文件夹,在其内新建一个文件index.js,在index.js对vuex进行初始化。
import Vuex from 'vuex'
import Vue from 'vue'
Vue.use(Vuex)
export default new Vuex.store({
//定义数据
state,
//改变数据
mutations,
//异步操作
actions,
//计算
getters,
//模块
modules
})
以上步骤创建完毕后,在main.js文件中对vuex进行导入,同时定义全局$store。
import store from './store/index.js'
Vue.prototype.$store=store
1.2 state定义数据
在/store/index.js
state:{
gTitle:{
text:"你好vuex",
color:"#000",
fontSize:"24px",
background:"#f70"
}
},
在页面中进行使用时$store.state.gTitle.text。引用时也可以使用简写形式,首先引入state的简写import {mapState} from 'vuex',其次在computed模块内把全局的vuex数据转换为组件只读的数据...mapState{["gTitle"]},最后可以直接使用gTitle进行引用。
1.3 mutations改变数据
mutations是改变state数据的唯一途径,在index.js的mutations模块中设置改变state数据的方式setFontSize(state,data){state.gTitle.fontSize=data+"px"},在页面使用时this.$store.commit("setFontSize",e.detail.value),简写方式为引入import {mapMutations} from 'vuex',定义methods:{...mapMutations(["setFontSize"])} ,使用 this.setFontSize(100)。
1.4 actions异步操作
在与后端交互中,异步操作都放在action