前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >uniapp小程序目录

uniapp小程序目录

作者头像
tianyawhl
发布2021-01-06 21:49:11
8950
发布2021-01-06 21:49:11
举报
文章被收录于专栏:前端之攻略前端之攻略

采用的ui为Uview

http.api.js

代码语言:javascript
复制
// 如果没有通过拦截器配置域名的话,可以在这里写上完整的URL(加上域名部分)
let hotSearchUrl = '/ebapi/store_api/hot_search';
let indexUrl = '/ebapi/public_api/index';

// 此处第二个参数vm,就是我们在页面使用的this,你可以通过vm获取vuex等操作,更多内容详见uView对拦截器的介绍部分:
// https://uviewui.com/js/http.html#%E4%BD%95%E8%B0%93%E8%AF%B7%E6%B1%82%E6%8B%A6%E6%88%AA%EF%BC%9F
const install = (Vue, vm) => {
	// 此处没有使用传入的params参数
	let login = (params = {}) => vm.$u.get(`wx/user/${params.appId}/login`, params);
	// 授权
	let auth = (params = {}) => vm.$u.get(`wx/user/${params.appId}/auth`, params);
	// 此处使用了传入的params参数,一切自定义即可
	// let getInfo = (params = {}) => vm.$u.post(indexUrl, params);
	
	// 将各个定义的接口名称,统一放进对象挂载到vm.$u.api(因为vm就是this,也即this.$u.api)下
	vm.$u.api = {login,auth};
}

export default {
	install
}

http.interceptor.js

代码语言:javascript
复制
// 这里的vm,就是我们在vue文件里面的this,所以我们能在这里获取vuex的变量,比如存放在里面的token变量
const install = (Vue, vm) => {
	// 此为自定义配置参数,具体参数见上方说明
	Vue.prototype.$u.http.setConfig({
			baseUrl: Vue.prototype.baseUrl, // 请求的本域名
			method: 'POST',
			// 设置为json,返回后会对数据进行一次JSON.parse()
			dataType: 'json',
			showLoading: true, // 是否显示请求中的loading
			loadingText: '请求中...', // 请求loading中的文字提示
			loadingTime: 800, // 在此时间内,请求还没回来的话,就显示加载中动画,单位ms
			originalData: false, // 是否在拦截器中返回服务端的原始数据
			loadingMask: true, // 展示loading的时候,是否给一个透明的蒙层,防止触摸穿透
			// 配置请求头信息
			header: {
				'content-type': 'application/json;charset=UTF-8'
			},
	});
	
	// 请求拦截,配置Token等参数
	Vue.prototype.$u.http.interceptor.request = (config) => {
		if(config.url.search(`/wx/user/${Vue.prototype.appid}/login`) === -1){
			config.header.Authorization = "wx " +uni.getStorageSync("token")
		}else{
			config.headers.Authorization = ''
		}
		// 引用token
		// 方式一,存放在vuex的token,假设使用了uView封装的vuex方式
		// 见:https://uviewui.com/components/globalVariable.html
		// config.header.token = vm.token;
		
		// 方式二,如果没有使用uView封装的vuex方法,那么需要使用$store.state获取
		// config.header.token = vm.$store.state.token;
		
		// 方式三,如果token放在了globalData,通过getApp().globalData获取
		// config.header.token = getApp().globalData.username;
		
		// 方式四,如果token放在了Storage本地存储中,拦截是每次请求都执行的
		// 所以哪怕您重新登录修改了Storage,下一次的请求将会是最新值
		// const token = uni.getStorageSync('token');
		// config.header.token = token;
		// config.header.Token = 'xxxxxx';
		
		// 可以对某个url进行特别处理,此url参数为this.$u.get(url)中的url值
		// if(config.url == '/user/login') config.header.noToken = true;
		// 最后需要将config进行return
		return config;
		// 如果return一个false值,则会取消本次请求
		// if(config.url == '/user/rest') return false; // 取消某次请求
	}
	
	// 响应拦截,判断状态码是否通过
	Vue.prototype.$u.http.interceptor.response = (res) => {
		return res
		// if(res.code == 200) {
		// 	// res为服务端返回值,可能有code,result等字段
		// 	// 这里对res.result进行返回,将会在this.$u.post(url).then(res => {})的then回调中的res的到
		// 	// 如果配置了originalData为true,请留意这里的返回值
		// 	return res.result;
		// } else if(res.code == 201) {
		// 	// 假设201为token失效,这里跳转登录
		// 	vm.$u.toast('验证失败,请重新登录');
		// 	setTimeout(() => {
		// 		// 此为uView的方法,详见路由相关文档
		// 		vm.$u.route('/pages/user/login')
		// 	}, 1500)
		// 	return false;
		// } else {
		// 	// 如果返回false,则会调用Promise的reject回调,
		// 	// 并将进入this.$u.post(url).then().catch(res=>{})的catch回调中,res为服务端的返回值
		// 	return false;
		// }
	}
}

export default {
	install
}

index.vue

代码语言:javascript
复制
<template>
	<view class="">
		<u-navbar :is-back="false" title="123" title-color="#fff" :background="background">

		</u-navbar>
		<button @getuserinfo="anthUserInfo" open-type="getUserInfo" type="default">用户授权</button>
		<view class="content">
			<u-icon name="photo"></u-icon>
			{{getUserInfo.nickName}}
		</view>
	</view>

</template>

<script>
	import {
		mapGetters,
		mapActions
	} from "vuex"
	export default {
		data() {
			return {
				userInfo:{},
				title: 'Hello',
				background: {
					// backgroundColor: '#001f3f'
					backgroundImage: 'linear-gradient(45deg, #ff9a9e 0%, #fad0c4 99%, #fad0c4 100%)'
				}
			}
		},
		computed: {
			...mapGetters(["getUserInfo","getNeedAuth","getIsLogin"])
		},
		onLoad() {
			if(!this.mapActions){
				this.init()
			}
			
		},
		methods: {
			...mapActions(["login","anthUserInfo"]),
			init(){
				this.login()
			}
			// login() {
			// 	uni.login({
			// 		provider: "weixin",
			// 		success: res => {
			// 			console.log(res)
			// 			this.$u.api.login({
			// 				appId: this.appId,
			// 				code: res.coad,
			// 				token: uni.getStorageSync("token")
			// 			}).then(res => {
			// 				uni.setStorageSync("token", res.token)
			// 			})
			// 		}
			// 	})
			// },
			// anthUserInfo() {
			// 	uni.getUserInfo({
			// 		provider: "weixin",
			// 		lang: "zh_CN",
			// 		success: res => {
			// 			console.log(JSON.stringify(res))
			// 			this.userInfo = {
			// 				nickName:res.userInfo.nickName,
			// 				sex:res.userInfo.gender,
			// 				city:res.userInfo.city,
			// 				province:res.userInfo.province
			// 			}
			// 			console.log(this.userInfo)
			// 			this.$u.api.auth(this.userInfo).then(res=>{
			// 				console.log(res)
			// 			})
			// 		}
			// 	})
			// }
		}
		}
</script>

<style>

</style>

store/index.js

代码语言:javascript
复制
import Vue from "vue"
import Vuex from "vuex"
Vue.use(Vuex)

const store = new Vuex.Store({
			state: {
				userInfo: {},
				needAuth: true,
				isLogin: false
			},
			getters: {
				getUserInfo(state) {
					return state.userInfo
				},
				getNeedAuth(state) {
					return state.needAuth
				},
				getIsLogin(state) {
					return state.isLogin
				}
			},
			mutations: {
				setUserInfo(state, userinfo) {
					state.userInfo = userinfo
				},
				setNeedAuth(state, needAuth) {
					state.needAuth = needAuth
				},
				setIsLogin(state, isLogin) {
					state.isLogin = isLogin
				}
			},
			actions: {
				login(context) {
					return new Promise((reslove, reject) => {
						uni.login({
							provider: "weixin",
							success: res => {
								console.log(res)
								return
								Vue.prototype.$u.api.login({
									appId: Vue.prototype.appId,
									code: res.coad,
									token: uni.getStorageSync("token")
								}).then(res => {
									uni.setStorageSync("token", res.token)
									if (res.msg == "登陆成功") {
										context.commit("setUserInfo", res.data.user)
										context.commit("setNeedAuth", false)
										context.commit("setIsLogin", true)
									}
									reslove("login执行完毕")
								})
							},
							fail: res => {
								Vue.prototype.$u.toase("fail")
								reject("fail")
							}
						})
					})


				},
				anthUserInfo(context) {
					return new Promise((resolve, reject) => {
						uni.getUserInfo({
							provider: "weixin",
							lang: "zh_CN",
							success: res => {
								console.log(JSON.stringify(res))
								let userInfo = {
									nickName: res.userInfo.nickName,
									sex: res.userInfo.gender,
									city: res.userInfo.city,
									province: res.userInfo.province
								}
								context.commit("setUserInfo", userInfo)
								console.log(context.state.userInfo)
								Vue.prototype.$u.api.auth(context.state.userInfo).then(res => {
									console.log(res)
									if (res.msg == "授权成功") {
										context.commit("setNeedAuth", false)
									} else {
										Vue.prototype.$u.toast("授权失败")
									}
									resolve("授权结束")

								})
							},
							fail:err=>{
								reject("授权失败")
							}

						})

					})
				}
			}
			})
			export default store

APP.vue

代码语言:javascript
复制
<script>
	export default {
		onLaunch: function() {
			console.log('App Launch')
		},
		onShow: function() {
			console.log('App Show')
		},
		onHide: function() {
			console.log('App Hide')
		}
	}
</script>

<style lang="scss">
	/* 注意要写在第一行,同时给style标签加入lang="scss"属性 */
	@import "uview-ui/index.scss";
</style>

main.js

代码语言:javascript
复制
import Vue from 'vue'
import App from './App'
import uView from "uview-ui";

Vue.use(uView);
import store from "./store/index.js"
Vue.config.productionTip = false
Vue.prototype.baseUrl = ""
Vue.prototype.appId = "wx6ed90ed13099c6ae"

App.mpType = 'app'

const app = new Vue({
	store,
    ...App
})
// http拦截器,此为需要加入的内容,如果不是写在common目录,请自行修改引入路径
import httpInterceptor from '@/common/http.interceptor.js'
// 这里需要写在最后,是为了等Vue创建对象完成,引入"app"对象(也即页面的"this"实例)
Vue.use(httpInterceptor, app)
// http接口API集中管理引入部分
import httpApi from '@/common/http.api.js'
Vue.use(httpApi, app)

app.$mount()

如果在小程序开发工具中运行

pages.json

代码语言:javascript
复制
{
	"easycom": {
		"^u-(.*)": "uview-ui/components/u-$1/u-$1.vue"
	},
	"pages": [ //pages数组中第一项表示应用启动页,参考:https://uniapp.dcloud.io/collocation/pages
		{
			"path": "pages/index/index",
			"style": {

			}
		},
		{
			"path": "pages/about/about",
			"style": {

			}
		}
	],
	"globalStyle": {
		"navigationStyle":"custom"
	},
	"tabBar": {
		"borderStyle": "black",
		"backgroundColor": "white",
		"color": "#8a8a8a",
		"selectedColor": "red",
		"list":[
			{
				"pagePath": "pages/index/index",
				"iconPath": "static/logo.png",
				"selectedIconPath": "static/logo.png",
				"text": "首页"
			},
			{
				"pagePath": "pages/about/about",
				"iconPath": "static/logo.png",
				"selectedIconPath": "static/logo.png",
				"text": "我的"
			}
		]
	}

}
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
相关产品与服务
云开发 CloudBase
云开发(Tencent CloudBase,TCB)是腾讯云提供的云原生一体化开发环境和工具平台,为200万+企业和开发者提供高可用、自动弹性扩缩的后端云服务,可用于云端一体化开发多种端应用(小程序、公众号、Web 应用等),避免了应用开发过程中繁琐的服务器搭建及运维,开发者可以专注于业务逻辑的实现,开发门槛更低,效率更高。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档