uniapp引入公共函数的两种方式
admin
2022-08-31 20:34:00
1、common文件夹下新建公共方法public.js
2、在main.js挂载
- export default {
- /*
- *字符串过程省略的函数
- *str 字符串
- *num 允许不被省略的长度
- */
- string_part_omit(str,num){
- if(str.length>num){
- str=str.substring(0,num)+"...";
- }
- return str;
- }
- }
在页面直接运用
- //公共函数引入
- import $public from './common/public.js'
- Vue.prototype.$public = $public
也可以在挂载的时候,直接挂载方法
- <view class="right">
- {{$public.string_part_omit(user.descr,10)}}
- </view>
- import $public from './common/public.js'
- Vue.prototype.$string_part_omit = $public.string_part_omit
2、common下封装常用函数
(1)可以直接在需要使用的时候引入该js import until from ‘@/util/common.js’;
- 文件:StrUtils.js
- //文件主要写的是会经常使用到的工具类
- //校验邮箱格式
- function checkEmail(email){
- return RegExp(/^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/).test(email);
- }
- //校验手机格式
- function checkMobile(mobile){
- return RegExp(/^1[34578]\d{9}$/).test(mobile);
- }
- module.exports = {
- checkEmail : checkEmail,
- checkMobile : checkMobile
- }
(2)也可以挂载到全局main.js里边
- if (!until.checkEmail(this.eml)) {
- uni.showToast({ title: '邮箱格式错误', icon: 'none' });
- return;
- }
使用方式:this.$common.checkEmail()
- import common from './util/common.js'
- Vue.prototype.$common = common;//挂载全局函数
¥ 打赏
×
如果您觉得文章帮助了您就打赏一下吧
非常感谢你的打赏,我们将继续分享更多优质内容,让我们一起创建更加美好的网络世界!

支付宝扫一扫打赏

微信扫一扫打赏
本文《uniapp引入公共函数的两种方式》发布于石头博客文章,作者:admin,如若转载,请注明出处:https://www.pweb123.com/frame/uniapp/902.html,否则禁止转载,谢谢配合!
上一篇:uniapp的生命周期函数
文章点评