0
点赞
收藏
分享

微信扫一扫

uni-app进阶使用(vuex、组件、api)

陌岛 2022-12-04 阅读 136

        在上一篇文章介绍了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异步操作

        在与后端交互中,异步操作都放在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})
}
}

1.5 getters 计算

        用于内部计算,根据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五个模块。

二、api使用

2.1 uni.getSystemInfoSync() 获取系统信息

        常用于获取屏幕宽高、系统、品牌、brand、可使用窗口顶部位置、安全区域等信息。

<template>
	<view>
		<view>屏幕宽高{{info.screenWidth}},{{info.screenHeight}}</view>
		<view>系统 {{info.osName}}</view>
		<view>品牌 {{info.model}}</view>
		<view>brand {{info.brand}}</view>
		<view>可使用的窗口顶部位置 {{info.windowTop}}</view>
		<view>安全区域 {{JSON.stringify(info.safeArea)}}</view>
		<view>安全区域 {{JSON.stringify(info.safeAreaInsets)}}</view>
</template>

<script>
	export default {
		data() {
			return {
				info:{},
			}
		},
		onLoad() {
			//获取系统信息
			var info=uni.getSystemInfoSync();
			this.info=info;
			console.log(this.info);
			//存储api
			uni.setStorageSync("info",info);
		}
    }

2.2 获取胶囊信息uni.getMenuButtonBoundingClientRect() 

        这个功能一般只用于微信小程序。

<template>
	<view>
		<!-- #ifdef MP -->
		<view>胶囊微信小程序</view>
		<view>导航栏高度{{(menuButtonInfo.top-info.statusBarHeight)*2+menuButtonInfo.height}}</view>
		<view>胶囊{{JSON.stringify(menuButtonInfo)}}</view>
		<!-- #endif -->
	</view>
</template>

<script>
	export default {
		data() {
			return {
				menuButtonInfo:{}
			}
		},
		onLoad() {
			//获取胶囊按钮的边界
			let menuButtonInfo=uni.getMenuButtonBoundingClientRect();
			this.menuButtonInfo=menuButtonInfo;
			console.log(menuButtonInfo);
		},

2.3 图片操作的api

        上传图片,使用uni.chooseImage()选择图片,其内部嵌套uni.uploadFile()。

        单击图片实现图片预览模式uni.previewImage(),在接口内部可以实现分享uni.share(),保存uni.saveImageToPhotosAlbum()等功能,使用时注意嵌套的层级关系。

<template>
<view>
<view>图片操作</view>
<view>选择与预览图片</view>
<button @click="selectPic">选择</button>
<view v-for="item in list" :key="item" @click="preview(item)">
<image :src="item"></image>
</view>
</view>
</template>

<script>
export default {
data() {
return {
}
},
methods: {
preview(item){
var that=this;
//单击图片实现预览
uni.previewImage({
//预览的图片列表
urls:this.list,
current:item,//当前图片
longPressActions:{
//定义长按按钮
itemList:['发送给朋友','保存图片','收藏'],
success:function(data){
console.log('选中了第'+(data.tapIndex+1)+'个按钮,第'+(data.index+1)+'张图片');
//保存
if(data.tapIndex==1){
//保存到本地相册
uni.saveImageToPhotosAlbum({
filePath:that.list[data.index],
success() {
uni.showToast({
title:"保存成功"
})
}
})
}
//分享
if(data.tapIndex==0){
//分享给朋友 (app打包时候分享要去微信的开发平台注册)
uni.share({
provider:"weixin",
scene:"WXSceneSession",
type:2,
imageUrl:that.list[data.index],
success:function(res){
console.log("success:"+JSON.stringify(res));
},
fail:function(err){
console.log("fail:"+JSON.stringify(err));
}
})
}
},
fail:function(err){
console.log(err.errMsg);
}
}
})
},
selectPic(){
var that=this;
//选择图片
uni.chooseImage({
count:3,//默认选3张
success(res){
//遍历结果的
for(let i=0;i<res.tempFilePaths.length;i++){
//上传图片
uni.uploadFile({
//上传地址
url:'http://520mg.com/ajax/file.php',
//图片信息
filePath:res.tempFilePaths[i],
//name需要和后端约定,默认都会叫file
name:'file',
success:result=>{
//转换为json
var data=JSON.parse(result.data);
//添加域名后加入list
that.list.push("http://520mg.com"+data.pic);
}
})
}
}
})
}
}
}
</script>

三、组件的使用

3.1 自定义组件

        自定义组件使用easycom方式,使用方式较vue简便了很多。组件定义完以后,可以不用import 导入,不用在components中注册,直接使用。

3.2 组件传参

        父组件向子组件传参,通过属性的方式进行传递<steper :value="d1"></steper>,子组件通过props来接收props:{ value:{ type:Number, default:1 ​} ​}。 

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

3.3 uni-app官网组件

        官方网址:组件使用的入门教程 | uni-app官网 ;路径:首页->组件->扩展组件,里面有大量封装好的组件,比较常用的有倒计时组件uni-countdown、轮播图组件uni-swiper-dot、弹框组件uni-popup等。

        在项目根目录下新建uni_modules 文件夹,单独安装需要的某个组件。下表为uni-ui的扩展组件清单,点击每个组件在详情页面可以导入组件到项目下,导入后直接使用即可,无需import和注册。

 3.4 第三方组件

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

        如果对你有用,欢迎收藏~

 

举报

相关推荐

0 条评论