uni-app

一、uni-app中全局引入weapp

(使用方法2)

二、uni-app中引入第三方自定义tabbar(使用官方插件市场的插件)

三、uni-app中使用uni-request发送网络请求

  • 方法1

1.在根目录下打开powershell窗口,把项目变成node项目

npm init -y
复制代码

2.安装uni-request

www.cnblogs.com/syncmr/p/11…

3.新建目录utils/request.js

import uniRequest from 'uni-request';

uniRequest.defaults.baseURL = 'http://jsonplaceholder.typicode.com';

// 请求拦截
uniRequest.interceptors.request.use(
	request => {
		//配置基本信息	
		return request;
	},
	err => {
		console.log('请求失败');
		return Promise.reject(err);
	});

// 响应拦截
uniRequest.interceptors.response.use(function(response) {
	console.log('返回进入拦截成功')
	return Promise.resolve(response);
}, function(error) {
	console.log('返回进入拦截失败')
	return Promise.reject(error);
});

export default uniRequest 
复制代码

4.在pages/index/index.vue中请求数据

<template>
	<view class="content">
		<!-- <image class="logo" src="https://juejin.cn/static/logo.png"></image>
		<view class="text-area">
			<text class="title">{{title}}</text>
		</view> -->
		<van-grid column-num="3">
		  <van-grid-item icon="photo-o" text="文字" v-for="item in 6" :key="item" />
		</van-grid>
		
		<van-button type="default">默认按钮</van-button>
		<van-button type="primary">主要按钮</van-button>
		<van-button type="info">信息按钮</van-button>
		<van-button type="warning">警告按钮</van-button>
		<van-button type="danger">危险按钮</van-button>
	</view>
</template>

<script>
	 import uniRequest from '../../untils/request.js'
	export default {
		data() {
			return {
				title: 'Hello'
			}
		},
		onLoad() {
		  uniRequest.get('/todos').then(res=>{
		  		console.log(res);
		  	})
		},
		methods: {
		
		},
		computed:{
			
		}
	}
</script>

<style>
	.content {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
	}

	.logo {
		height: 200rpx;
		width: 200rpx;
		margin-top: 200rpx;
		margin-left: auto;
		margin-right: auto;
		margin-bottom: 50rpx;
	}

	.text-area {
		display: flex;
		justify-content: center;
	}

	.title {
		font-size: 36rpx;
		color: #8f8f94;
	}
</style>

复制代码

运行到浏览器后得到打印的数据

  • 方法2

1.新建目录api/info.js

import uniRequest from '../untils/request.js'

export const getTodos=()=>{
  return uniRequest({
    method:'get',
    url:'/todos'
  })
}
复制代码

2.pages/index/index.vue

<template>
	<view class="content">
		<!-- <image class="logo" src="https://juejin.cn/static/logo.png"></image>
		<view class="text-area">
			<text class="title">{{title}}</text>
		</view> -->
		<van-grid column-num="3">
		  <van-grid-item icon="photo-o" text="文字" v-for="item in 6" :key="item" />
		</van-grid>
		
		<van-button type="default">默认按钮</van-button>
		<van-button type="primary">主要按钮</van-button>
		<van-button type="info">信息按钮</van-button>
		<van-button type="warning">警告按钮</van-button>
		<van-button type="danger">危险按钮</van-button>
		<view class="">{{$store.state.count}}</view>
		<view class="">{{count}}</view>
		<button type="default" @tap="add">+</button>
	</view>
</template>

<script>
	// import uniRequest from '../../untils/request.js'
	import {getTodos} from '../../api/info.js'
	export default {
		data() {
			return {
				title: 'Hello'
			}
		},
		onLoad() {
		// uniRequest.get('/todos').then(res=>{
		// 		console.log(res);
		// 	})
		
			getTodos().then(res=>{
				console.log(res)
			})
		},
		methods: {
		
		},
		computed:{
			
		}
	}
</script>

<style>
	.content {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
	}

	.logo {
		height: 200rpx;
		width: 200rpx;
		margin-top: 200rpx;
		margin-left: auto;
		margin-right: auto;
		margin-bottom: 50rpx;
	}

	.text-area {
		display: flex;
		justify-content: center;
	}

	.title {
		font-size: 36rpx;
		color: #8f8f94;
	}
</style>

复制代码
  • 或者可以使用自己封装的request.js(不需要装包)
const host = 'http://jsonplaceholder.typicode.com'

const request = ({url,method='Get',data,header}) => {
	// 请求之前提示加载中
	uni.showLoading({title: '加载中...'})
	return new Promise((resolve, reject) => {
		uni.request({
			url: host + url,
			method: method,
			data: method === 'GET' ? data : JSON.stringify(data),
			header: header ||{
				'Content-Type': 'application/json; charset=UTF-8',
				'x-token': 'x-token' // 看自己是否需要
			},
			success: resolve,
			fail: reject,
			complete() {
				uni.hideLoading()
			}
		})
	})
}
export default request

复制代码

info.js

import request from '../untils/request.js'

export const getTodos=()=>{
  return request({
    method:'get',
    url:'/todos'
  })
}
复制代码

四、uni-app中使用vuex

  • uni-app已经自动下载了vuex,只需要引用就行

1.新建目录store/index.js

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

const store = new Vuex.Store({
	state:{
		count:0
	},
	mutations:{
		add(state){
			state.count++
		}
	}
})
export default store
复制代码

2.配置全局(main.js)

import Vue from 'vue'
import App from './App'
import store from './store/index.js'

Vue.config.productionTip = false

App.mpType = 'app'

Vue.prototype.$store=store

const app = new Vue({
    ...App
})
app.$mount()

复制代码

3.在pages/index/index.vue中渲染(使用)

<template>
	<view class="content">
		<!-- <image class="logo" src="https://juejin.cn/static/logo.png"></image>
		<view class="text-area">
			<text class="title">{{title}}</text>
		</view> -->
		<van-grid column-num="3">
		  <van-grid-item icon="photo-o" text="文字" v-for="item in 6" :key="item" />
		</van-grid>
		
		<van-button type="default">默认按钮</van-button>
		<van-button type="primary">主要按钮</van-button>
		<van-button type="info">信息按钮</van-button>
		<van-button type="warning">警告按钮</van-button>
		<van-button type="danger">危险按钮</van-button>
		<view class="">{{$store.state.count}}</view>
		<view class="">{{count}}</view>
		<button type="default" @tap="add">+</button>
	</view>
</template>

<script>
	// import uniRequest from '../../untils/request.js'
	import {getTodos} from '../../api/info.js'
	import {mapState,mapMutations} from 'vuex'
	export default {
		data() {
			return {
				title: 'Hello'
			}
		},
		onLoad() {
		// uniRequest.get('/todos').then(res=>{
		// 		console.log(res);
		// 	})
		
			getTodos().then(res=>{
				console.log(res)
			})
		},
		methods: {
		...mapMutations(['add'])
		},
		computed:{
			...mapState(['count'])
		}
	}
</script>

<style>
	.content {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
	}

	.logo {
		height: 200rpx;
		width: 200rpx;
		margin-top: 200rpx;
		margin-left: auto;
		margin-right: auto;
		margin-bottom: 50rpx;
	}

	.text-area {
		display: flex;
		justify-content: center;
	}

	.title {
		font-size: 36rpx;
		color: #8f8f94;
	}
</style>

复制代码

五、uni-app-cloud项目创建并请求数据库数据

1.新建项目,启用uniCloud,使用阿里云

image.png

2.选择要绑定的服务空间

image.png

  • 如果没有就新建一个

image.png

  • 创建好之后显示下图

image.png

3.在云数据库中创建表

image.png

4.在表中导入数据

image.png

5.关联云服务空间,并运行一下项目

image.png

image.png

  • 下图方式用不了

image.png

  • 换一种方式,使用云函数
  • 1.创建云函数shops

image.png

  • 2.访问数据库规范

image.png

  • 3.云函数get_shops
'use strict';
const db = uniCloud.database();
const collection= db.collection('shops')
exports.main = async (event, context) => {
	//event为客户端上传的参数
	// console.log('event : ', event)
	const res=await collection.get()
	console.log(res)
	//返回数据给客户端
	return res
};

复制代码
  • 在本地运行云函数,进行测试

image.png

  • 4.在pages/index/index.vue获取数据,如果返回的result是空值,说明云函数没有返回res
onLoad() {
	uniCloud.callFunction({
            name:'get_shops'
	}).then(res=>{
            console.log(res)
	})
},
复制代码

image.png

  • 云函数每次修改后需要重新上传

image.png

6.uniCloud使用db_init.json快速生成数据库(将所需要的获取的数据放入db_init.json)

image.png

  • 注意数据格式:

image.png

  • 6.在db_init.json中填写数据后,右击初始化云数据库
  • 7.在uni-app云数据库中刷新数据库表

7.uniCloud生成db_init.json

8.uni-app云存储和图片上传

  • 1.给按钮绑定点击事件
<button type="default" @tap="upload">上傳</button>
复制代码
  • 2.实现点击上传图片
methods: {
			upload(){
				//前端代码
				uni.chooseImage({
				    count: 1,
				    async success(res) {
				        console.log(res);
				        if (res.tempFilePaths.length > 0) {
				            let filePath = res.tempFilePaths[0]
				            //进行上传操作
				
				            // promise方式
				    //         const result = await uniCloud.uploadFile({
				    //             filePath: filePath,
								// cloudPath: 'a.jpg',
				    //             onUploadProgress: function(progressEvent) {
				    //                   console.log(progressEvent);
				    //                   var percentCompleted = Math.round(
				    //                     (progressEvent.loaded * 100) / progressEvent.total
				    //                   );
				    //                 }
				    //         });
				
				            // callback方式,与promise方式二选一即可
				            uniCloud.uploadFile({
				                filePath: filePath,
				        cloudPath: 'a.jpg',
				        onUploadProgress: function(progressEvent) {
				          console.log(progressEvent);
				          var percentCompleted = Math.round(
				            (progressEvent.loaded * 100) / progressEvent.total
				          );
				                },
				                success() {},
				                fail() {},
				                complete() {}
				            });
				
				        }
				    }
				});
				}
			}
复制代码
© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享