uniapp和vue什么关系_uniapp使用vuex

uniapp和vue什么关系_uniapp使用vuexuniapp从零开始搭建前言1.开发工具 HBuilder 2.Node.js (18.12.1)3.npm(9.1.2)4.模拟器:夜神模拟器5.技术选型UI框架:uni-ui多语言:vue-i18n多主题:scss状态管理:vuexHTTP请求库: luch-request6.目录结

uniapp从零开始搭建

前言

1.开发工具 HBuilder

2.Node.js (18.12.1)

3.npm(9.1.2)

4.模拟器:夜神模拟器

5.技术选型

  • UI框架:uni-ui
  • 多语言:vue-i18n
  • 多主题:scss
  • 状态管理:vuex
  • HTTP请求库: luch-request

6.目录结构


uniapp和vue什么关系_uniapp使用vuex

项目创建

1.uni-ui

打开HBuilder 左上角 文件-> 项目 -> 选择uni-ui项目 – 版本vue2 – 创建

  • manifest.json 配置

uniapp和vue什么关系_uniapp使用vuex
  • 自定义标题栏(pages.json)
// 禁止滚动
{
			"path": "pages/index",
			"style": {
				"navigationStyle": "custom"
			}
},
// 可下拉刷新
{
			"path": "pages/index",
			"style": {
				"enablePullDownRefresh": true,
				"onReachBottomDistance": 100
			}
},
"globalStyle": {
		"backgroundColor": "#f4f4f4",
		"navigationStyle": "custom"
}
  • Navbar.vue(自定义标题栏组件)
<template>
	<view style="box-shadow: 0rpx 0rpx 10rpx 2rpx #efefef;">
		<uni-nav-bar :title="title" :color="color" :backgroundColor="backgroundColor" :fixed="fixed" :border="border"
			 :style="{paddingTop:getSystemInfo().statusBarHeight + 'px'}"></uni-nav-bar>
	</view>
</template>

<script>
	export default {
		props: {
			title: {
				type: String,
				default: ''
			},
			shadow: {
				type: Boolean,
				default: true
			},
			border: {
				type: Boolean,
				default: false
			},
			fixed: {
				type: Boolean,
				default: false
			},
			color: {
				type: String,
				default: "#303133"
			},
			backgroundColor: {
				type: String,
				default: "#fff"
			}
		},
		data() {
			return {}
		},
		created() {
		}

	}
</script>

<style>
</style>
  • 自定义底部菜单栏

2.vue-i18n

npm install vue-i18n
  • 提供一个向外暴露的i18n方法 (文件路径:comon/i18n/index.js,参考目录结构)
import Vue from 'vue'
import VueI18n from 'vue-i18n'
import zh from 'https://zhuanlan.zhihu.com/p/language/zh'
import en from 'https://zhuanlan.zhihu.com/p/language/en'
Vue.use(VueI18n);
const i18n = new VueI18n({
	locale: 'zh',
	messages: {
		'en': en,
		'zh': zh
	}
})
export default i18n;
// main.js
  • 提供一个向外暴露的多语言 中文 (文件路径:comon/i18n/language/zh.js,参考目录结构)
export default { 
    list:{ 
        name:'我的博客', 
        Professional:'Web前端工程师', 
        data:[ 
            { text:'全部文章' }, 
            { text:'我的npm' }, 
            { text:'项目库' }, 
            { text:'软件分享' }, 
            { text:'图片分享' }, 
            { text:'我的简历' }, 
        ] }, 
        Page:{ 
            index:{ 
                title:'欢迎我的朋友', 
            } 
        } 
 }
  • main.js
import i18n from '@/common/i18n/index'
const app = new Vue({
    ...App,
    i18n, 
})
  • 使用
{{$t(`list.name`)}}

3.http请求封装

npm install luch-request
  • 提供一个向外暴露的http方法 (文件路径:comon/http/index.js,参考目录结构)
import Request from 'luch-request' // 使用npm
const http = new Request();

/****************************************************************
 *   初始化请求配置
 ***************************************************************/
http.setConfig((defaultConfig) => {
	/* 根域名 */
	defaultConfig.baseURL = "http://localhost:8080/";
	defaultConfig.header = {
		'content-type': "application/json;charset=UTF-8;",
	}
	return defaultConfig;
});

/****************************************************************
 *   请求拦截
 ***************************************************************/
http.interceptors.request.use((config) => {
	uni.showLoading({ title: '加载中' });
	config.data = config.data || {};
	// cookie 不存在跳转登录页面
	let Authorization = getTokenCookie();
	if (!Authorization) {
		// uni.reLaunch({url:ROUTERS.SYSTEM.LOGIN});
	}
	config.header = {
		...config.header,
		'Authorization': Authorization
	}
	return config;
}, (config) => Promise.reject(config))

/****************************************************************
 *   响应拦截
 ***************************************************************/
http.interceptors.response.use((response) => {
	if (response.data) {
		if (response.data.statusCode == 200) {
			uni.hideLoading();
			return response.data;
		}
	}
	uni.hideLoading();
	return Promise.reject(response);
}, (response) => {
	uni.hideLoading();
	/* 301 401 返回重新登录 */
	if (response.statusCode == 401 || data.statusCode == 301) {
		// uni.reLaunch({ url: ROUTERS.SYSTEM.LOGIN });
	}
	return Promise.reject(response);
})

export default http;
  • main
import http from '@/common/http/index'
Vue.prototype.$http = http;
  • 使用参考 luch-request官方文档

4.Vuex

npm install vuex
  • 提供一个向外暴露的vuex方法 (文件路径:store,参考目录结构)
import Vue from 'vue'
import Vuex from 'vuex'
import userStore from 'https://zhuanlan.zhihu.com/p/modules/userStore'


Vue.use(Vuex);


const store = new Vuex.Store({
	modules: {
		userStore,
	}
})
export default store
  • 要是代码多了分模块
const userStore = {
	state:()=>({
		username:"zhan"
	}),
	actions:{
		loginSuccess(user){
			this.username = user.username;
		}
	},
	getters:{}
}
export default userStore;
  • main.js
import store from "https://zhuanlan.zhihu.com/p/store/index";
Vue.prototype.$store = store
const app = new Vue({
    ...App,
    store,
})
  • 使用
this.$store.state.userStore.username;

5.封装常用的公共方法

1.缓存

//  基本缓存方法
export function getCookie(key) {
	let str = uni.getStorageSync(key);
	return str;
}
export function setCookie(key, data) {
	uni.setStorageSync(key, data)
}
export function removeCookie(key) {
	uni.removeStorageSync(key);
}

2.路由跳转

ROUTER() {
			return {
				/**
				 * @url 路径 String
				 * @params 参数 String
				 * @type 跳转方式 String
				 */
				to: function(url, params = {}, tpye = "navigateTo") {
					if (tpye == 'navigateTo') {
						uni.navigateTo({
							url: url + '?' + transParams(params)
						});
					}
					if (tpye == 'redirectTo') {
						uni.redirectTo({
							url: url
						});
					}
					if (tpye == 'switchTab') {
						uni.switchTab({
							url: url
						});
					}
					if (tpye == 'reLaunch') {
						uni.reLaunch({
							url: url
						});
					}
					if (tpye == 'navigateBack') {
						uni.navigateBack();
					}
				},
				/**
				 * @delta 返回上 { n:number } 级 
				 */
				back: function(delta = 1) {
					uni.navigateBack(delta);
				}
			}
			
		}

3.常用方法

                 /**
		 * 复制内容到黏贴板
		 * @param {Object} str
		 */
		copy(str) {
			uni.setClipboardData({
				data: str,
				success: function() {
					uni.showToast({
						title: "Copy Successfully",
						duration: 2000,
						icon: 'none'
					});
				},
				fail(err) {
					uni.showToast({
						title: "Replication Failed:" + err,
						duration: 2000,
						icon: 'none'
					});
				}
			})
		},
		/**
		 * 消息提示
		 * @param {Object} title
		 */
		message(title) {
			if (title) {
				uni.showToast({
					title: title,
					duration: 2000,
					icon: 'none'
				});
			} else {
				return {
					ok: function() {
						uni.showToast({
							title: "操作成功",
							duration: 2000,
							icon: 'success'
						});
					},
					err: function(title) {
						uni.showToast({
							title: "操作失败",
							duration: 2000,
							icon: 'error'
						});
					}
				}

			}
		},
		/**
		 * 本地图片
		 * @param {Object} imagePath
		 */
		getImageStatic(imagePath) {
			return '/static/image/' + imagePath;
		},
		/**
		 * 保留小数点
		 * @value { number|string } 原数据
		 * @fractionDigits {number}  保留几位数  默认2位
		 */
		round(value, fractionDigits = 2) {
			var tens = Math.pow(10, fractionDigits);
			return Math.round(value * tens) / tens;
		},
		/**
		 * 检测时间差
		 * var now = new Date().getTime();
		 * checkTimeDiff(lastTime, now, 1)
		 * @param {Object} lastTime 
		 * @param {Object} now 当前时间
		 * @param {Object} timeDiffSecondsValues
		 */
		checkTimeDiff(lastTime, now, timeDiffSecondsValues) {
			if (!lastTime) {
				return true;
			}
			if (now - lastTime > timeDiffSecondsValues * 1000) {
				return true;
			}
			return false;
		},
		/**
		 * 替换字符串
		 * @str {string} stringFormat('测试{0}123{1}',"内容","完成")
		 */
		stringFormat(str, ...args) {
			if (!str) {
				return str;
			}
			for (var i = 0; i < args.length; i++) {
				var reg = new RegExp("({)" + i + "(})", "g");
				str = str.replace(reg, args[i]);
			}
			return str;
		},
/**
		 * @deviceId 		设备 id 
		 * 
		 * @appId	 		manifest 中应用appid,即DCloud appid。	
		 * @appName			manifest 中应用名称	
		 * @appVersion		manifest 中应用版本名称。	
		 * @appVersionCode	manifest 中应用版本名号。	
		 * 
		 * @screenWidth		屏幕宽度	
		 * @screenHeight	屏幕高度		
		 * @windowWidth		可使用窗口宽度		
		 * @windowHeight	可使用窗口高度		
		 * @windowTop		可使用窗口的顶部位置		
		 * @windowBottom	可使用窗口的底部位置			
		 * @statusBarHeight	手机状态栏的高度				
		 * 
		 * @deviceType 		设备类型。如phone、pad、pc、unknow	
		 * @deviceBrand 	设备品牌。如:apple、huawei	
		 * @deviceModel 	设备型号	
		 * @osName 			系统名称	ios、android	
		 * @osVersion		操作系统版本。如 ios 版本,andriod 版本	
		 */
		getSystemInfo() {
			let systemInfo = {};
			uni.getSystemInfo({
				success: (e) => {
					systemInfo.deviceId = e.deviceId;
					
					systemInfo.appId = e.appId;
					systemInfo.appName = e.appName;
					systemInfo.appVersion = e.appVersion;
					systemInfo.appVersionCode = e.appVersionCode;
					
					systemInfo.screenWidth = e.screenWidth;
					systemInfo.screenHeight = e.screenHeight;
					systemInfo.windowWidth = e.windowWidth;
					systemInfo.windowHeight = e.windowHeight;
					systemInfo.windowTop = e.windowTop;
					systemInfo.windowBottom = e.windowBottom;
					systemInfo.statusBarHeight = e.statusBarHeight;
					
					systemInfo.deviceType = e.deviceType;
					systemInfo.deviceBrand = e.deviceBrand;
					systemInfo.deviceModel = e.deviceModel;
					systemInfo.osName = e.osName;
					systemInfo.osVersion = e.osVersion;
				}
			})
			return systemInfo;
		},

2024最新激活全家桶教程,稳定运行到2099年,请移步至置顶文章:https://sigusoft.com/99576.html

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。 文章由激活谷谷主-小谷整理,转载请注明出处:https://sigusoft.com/14060.html

(0)
上一篇 2024年 5月 16日 下午3:16
下一篇 2024年 5月 16日 下午4:02

相关推荐

关注微信