在上一篇文章介绍了uni-app的基本用法,本章介绍在uni-app中vuex、组件、api的用法。
在项目根目录下创建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
在/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进行引用。

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)。

在与后端交互中,异步操作都放在actions模块中进行。在index.js文件actions模块中
state:{joks:[]},
mutations:{setJoks(state,data){state.joks=data;}
},
actions:{getJok(context,data){uni.request({url:"http://520mg.com/mi/list.php",method:'get',data:data,//axios get 请求参数用params,post用data//uni.request post和get传参都用data//根据content-type,如果是application/json,那么data是json,如果是urlencoded data是url编码形式success: (res) => {console.log(res);context.commit('setJoks',res.data.result);}})}},
在使用页面中
export default {data() {return {}},onLoad() {this.$store.dispatch("getJok",{page:1})}
}
用于内部计算,根据state中的数据计算出新的数据(只读)。在index.js中定义getters:{"totalLen":function(state){return }},在使用页面中import {mapGetters} from "vuex"; computed:{...mapGetters(["totalLen"])} 使用时 this.totalLen。
1.6 modules模块
与vue中的vuex的modules用法相同,相当于vuex中套vuex使用。核心依然是state、mutations、actions、getters、modules五个模块。
常用于获取屏幕宽高、系统、品牌、brand、可使用窗口顶部位置、安全区域等信息。
屏幕宽高{{info.screenWidth}},{{info.screenHeight}} 系统 {{info.osName}} 品牌 {{info.model}} brand {{info.brand}} 可使用的窗口顶部位置 {{info.windowTop}} 安全区域 {{JSON.stringify(info.safeArea)}} 安全区域 {{JSON.stringify(info.safeAreaInsets)}}
自定义组件使用easycom方式,使用方式较vue简便了很多。组件定义完以后,可以不用import 导入,不用在components中注册,直接使用。

父组件向子组件传参,通过属性的方式进行传递

子组件向父组件传参,子组件通过this.$emit("事件名",传递的参数) 触发事件,父组件监听事件并更新值。

官方网址:组件使用的入门教程 | uni-app官网 ;路径:首页->组件->扩展组件,里面有大量封装好的组件,比较常用的有倒计时组件uni-countdown、轮播图组件uni-swiper-dot、弹框组件uni-popup等。
在项目根目录下新建uni_modules 文件夹,单独安装需要的某个组件。下表为uni-ui的扩展组件清单,点击每个组件在详情页面可以导入组件到项目下,导入后直接使用即可,无需import和注册。

uni-app有很多第三方插件,在官网点击插件市场,会有很多的资源选择,这里给大家推荐的的uview第三方插件。可通过使用HBuilderX导入插件和下载插件ZIP两种方式进行使用,具体安装和配置大家异步参考官网https://uviewui.com,很详细。
如果对你有用,欢迎收藏~