完成输入和单位换算一体组件

This commit is contained in:
RuoYi 2023-07-19 16:03:07 +08:00 committed by 廖德云
parent 295c0f2ced
commit c7b4db67bf
17 changed files with 1144 additions and 497 deletions

View File

@ -25,7 +25,7 @@ RuoYi App 移动解决方案采用uniapp框架一份代码多终端适配
- 官网网站:[http://ruoyi.vip](http://ruoyi.vip) - 官网网站:[http://ruoyi.vip](http://ruoyi.vip)
- 文档地址:[http://doc.ruoyi.vip](http://doc.ruoyi.vip) - 文档地址:[http://doc.ruoyi.vip](http://doc.ruoyi.vip)
- H5页体验[http://h5.ruoyi.vip](http://h5.ruoyi.vip) - H5页体验[http://h5.ruoyi.vip](http://h5.ruoyi.vip)
- QQ交流群 ①133713780 - QQ交流群 ①133713780(满)、②146013835
- 小程序体验 - 小程序体验
<img src="https://oscimg.oschina.net/oscnet/up-26c76dc90b92acdbd9ac8cd5252f07c8ad9.jpg" alt="小程序演示"/> <img src="https://oscimg.oschina.net/oscnet/up-26c76dc90b92acdbd9ac8cd5252f07c8ad9.jpg" alt="小程序演示"/>

47
api/system/conversion.js Normal file
View File

@ -0,0 +1,47 @@
import upload from '@/utils/upload'
import request from '@/utils/request'
// 查询单位换算列表
export function listConversion(query) {
return request({
url: '/system/conversion/list',
method: 'get',
params: query
})
}
// 查询单位换算详细
export function getConversion(id) {
return request({
url: '/system/conversion/' + id,
method: 'get'
})
}
// 新增单位换算
export function addConversion(data) {
return request({
url: '/system/conversion',
method: 'post',
data: data
})
}
// 修改单位换算
export function updateConversion(data) {
return request({
url: '/system/conversion',
method: 'put',
data: data
})
}
// 删除单位换算
export function delConversion(id) {
return request({
url: '/system/conversion/' + id,
method: 'delete'
})
}

View File

@ -1,7 +1,7 @@
// 应用全局配置 // 应用全局配置
module.exports = { module.exports = {
baseUrl: 'https://vue.ruoyi.vip/prod-api', // baseUrl: 'https://vue.ruoyi.vip/prod-api',
// baseUrl: 'http://localhost:8080', baseUrl: 'http://192.168.3.19:9090',
// 应用信息 // 应用信息
appInfo: { appInfo: {
// 应用名称 // 应用名称

View File

@ -1,23 +1,23 @@
{ {
"name" : "若依移动端", "name": "若依移动端",
"appid" : "__UNI__25A9D80", "appid": "__UNI__1347B29",
"description" : "", "description": "",
"versionName" : "1.1.0", "versionName": "1.1.0",
"versionCode" : "100", "versionCode": "100",
"transformPx" : false, "transformPx": false,
"app-plus" : { "app-plus": {
"usingComponents" : true, "usingComponents": true,
"nvueCompiler" : "uni-app", "nvueCompiler": "uni-app",
"splashscreen" : { "splashscreen": {
"alwaysShowBeforeRender" : true, "alwaysShowBeforeRender": true,
"waiting" : true, "waiting": true,
"autoclose" : true, "autoclose": true,
"delay" : 0 "delay": 0
}, },
"modules" : {}, "modules": {},
"distribute" : { "distribute": {
"android" : { "android": {
"permissions" : [ "permissions": [
"<uses-permission android:name=\"android.permission.CHANGE_NETWORK_STATE\"/>", "<uses-permission android:name=\"android.permission.CHANGE_NETWORK_STATE\"/>",
"<uses-permission android:name=\"android.permission.MOUNT_UNMOUNT_FILESYSTEMS\"/>", "<uses-permission android:name=\"android.permission.MOUNT_UNMOUNT_FILESYSTEMS\"/>",
"<uses-permission android:name=\"android.permission.VIBRATE\"/>", "<uses-permission android:name=\"android.permission.VIBRATE\"/>",
@ -35,35 +35,35 @@
"<uses-permission android:name=\"android.permission.WRITE_SETTINGS\"/>" "<uses-permission android:name=\"android.permission.WRITE_SETTINGS\"/>"
] ]
}, },
"ios" : {}, "ios": {},
"sdkConfigs" : {} "sdkConfigs": {}
} }
}, },
"quickapp" : {}, "quickapp": {},
"mp-weixin" : { "mp-weixin": {
"appid" : "wxccd7e2a0911b3397", "appid": "wxccd7e2a0911b3397",
"setting" : { "setting": {
"urlCheck" : false, "urlCheck": false,
"es6" : false, "es6": false,
"minified" : true, "minified": true,
"postcss" : true "postcss": true
}, },
"optimization" : { "optimization": {
"subPackages" : true "subPackages": true
}, },
"usingComponents" : true "usingComponents": true
}, },
"vueVersion" : "2", "vueVersion": "2",
"h5" : { "h5": {
"template" : "static/index.html", "template": "static/index.html",
"devServer" : { "devServer": {
"port" : 9090, "port": 9090,
"https" : false "https": false
}, },
"title" : "RuoYi-App", "title": "RuoYi-App",
"router" : { "router": {
"mode" : "hash", "mode": "hash",
"base" : "./" "base": "./"
} }
} }
} }

5
package.json Normal file
View File

@ -0,0 +1,5 @@
{
"dependencies": {
"bignumber.js": "^9.1.2"
}
}

View File

@ -0,0 +1,76 @@
/* ===pages-tool===
pages-tool使
pages-toolpages.josn便
使
,pages.json
pages.jsonpaes-config.jsonpages.josn,
pages.json
*/
{
//,globalStyle使pages.json
//"globalStyle" : "pages-config/globalStyle.json"
//pages.jsonglobalStyle
"globalStyle" : "",
//,easycom使pages.json
//"easycom" : "pages-config/easycom.json"
//pages.jsoneasycom
"easycom" : "",
//,tabBar使pages.json
//"tabBar" : "pages-config/tabBar.json"
//pages.jsontabBar
"tabBar" : "",
//,pages使pages.json
//"pages" : ["pages-config/pages-moduleA.json", "pages-config/pages-moduleB.json", "pages-config/pages-moduleC.json", ...]
//pages.jsonpages
"pages" : [],
//,condition使pages.json
//"condition" : "pages-config/condition.json"
//pages.jsoncondition
"condition" : "",
//,pages使pages.json
//"subPackages" : [pages-config/subPackages-moduleNameA.json, pages-config/subPackages-moduleNameB.json, ...],
//pages.jsonsubPackages
//pages
"subPackages" : [],
//,preloadRule使pages.json
//"preloadRule" : "pages-config/preloadRule.json"
//pages.jsonpreloadRule
"preloadRule" : "",
//"workers" : "pages-config/workers.json"
//pages.json
"workers" : "",
//,leftWindow使pages.json
//"leftWindow" : "pages-config/leftWindow.json"
//pages.jsonleftWindow
"leftWindow" : "",
//,topWindow使pages.json
//"topWindow" : "pages-config/topWindow.json"
//pages.jsontopWindow
"topWindow" : "",
//,rightWindow使pages.json
//"rightWindow" : "pages-config/rightWindow.json"
//pages.jsonrightWindow
"rightWindow" : "",
//,uniIdRouter使pages.json
//"uniIdRouter" : "pages-config/uniIdRouter.json"
//pages.jsonuniIdRouter
"uniIdRouter" : "",
//page.json
//"entryPagePath" : "/...." "entryPagePath" : "pages-config/entryPagePath.json"
"entryPagePath": ""
}

40
pages-config.json Normal file
View File

@ -0,0 +1,40 @@
/* ===pages-tool===
pages-tool
pages-toolpages.josn便
使
,pages.json
pages.jsonpaes-config.jsonpages.josn,
pages.json
*/
{
"globalStyle" : "pages-config/globalStyle.json",
"easycom" : "",
"tabBar" : "pages-config/tabBar.json",
"pages" : ["pages-config/pages-all.json"],
"condition" : "",
"leftWindow" : "",
"topWindow" : "",
"rightWindow" : "",
"uniIdRouter" : "",
///
"subPackages" : [],
"preloadRule" : "",
"workers" : "",
"entryPagePath": ""
}

View File

@ -0,0 +1,8 @@
/* /// Pages-Tool: pages-toolpages-config.json,pages.json*/
{
"globalStyle": {
"navigationBarTextStyle": "black",
"navigationBarTitleText": "RuoYi",
"navigationBarBackgroundColor": "#FFFFFF"
}
}

View File

@ -0,0 +1,75 @@
/* /// Pages-Tool: pages-toolpages-config.json,pages.json*/
{
"pages": [{
"path": "pages/login",
"style": {
"navigationBarTitleText": "登录"
}
}, {
"path": "pages/register",
"style": {
"navigationBarTitleText": "注册"
}
}, {
"path": "pages/index",
"style": {
"navigationBarTitleText": "若依移动端框架",
"navigationStyle": "custom"
}
}, {
"path": "pages/work/index",
"style": {
"navigationBarTitleText": "工作台"
}
}, {
"path": "pages/mine/index",
"style": {
"navigationBarTitleText": "我的"
}
}, {
"path": "pages/mine/avatar/index",
"style": {
"navigationBarTitleText": "修改头像"
}
}, {
"path": "pages/mine/info/index",
"style": {
"navigationBarTitleText": "个人信息"
}
}, {
"path": "pages/mine/info/edit",
"style": {
"navigationBarTitleText": "编辑资料"
}
}, {
"path": "pages/mine/pwd/index",
"style": {
"navigationBarTitleText": "修改密码"
}
}, {
"path": "pages/mine/setting/index",
"style": {
"navigationBarTitleText": "应用设置"
}
}, {
"path": "pages/mine/help/index",
"style": {
"navigationBarTitleText": "常见问题"
}
}, {
"path": "pages/mine/about/index",
"style": {
"navigationBarTitleText": "关于我们"
}
}, {
"path": "pages/common/webview/index",
"style": {
"navigationBarTitleText": "浏览网页"
}
}, {
"path": "pages/common/textview/index",
"style": {
"navigationBarTitleText": "浏览文本"
}
}]
}

25
pages-config/tabBar.json Normal file
View File

@ -0,0 +1,25 @@
/* /// Pages-Tool: pages-toolpages-config.json,pages.json*/
{
"tabBar": {
"color": "#000000",
"selectedColor": "#000000",
"borderStyle": "white",
"backgroundColor": "#ffffff",
"list": [{
"pagePath": "pages/index",
"iconPath": "static/images/tabbar/home.png",
"selectedIconPath": "static/images/tabbar/home_.png",
"text": "首页"
}, {
"pagePath": "pages/work/index",
"iconPath": "static/images/tabbar/work.png",
"selectedIconPath": "static/images/tabbar/work_.png",
"text": "计算工具"
}, {
"pagePath": "pages/mine/index",
"iconPath": "static/images/tabbar/mine.png",
"selectedIconPath": "static/images/tabbar/mine_.png",
"text": "我的"
}]
}
}

View File

@ -85,14 +85,13 @@
"pagePath": "pages/work/index", "pagePath": "pages/work/index",
"iconPath": "static/images/tabbar/work.png", "iconPath": "static/images/tabbar/work.png",
"selectedIconPath": "static/images/tabbar/work_.png", "selectedIconPath": "static/images/tabbar/work_.png",
"text": "工作台" "text": "计算工具"
}, { }, {
"pagePath": "pages/mine/index", "pagePath": "pages/mine/index",
"iconPath": "static/images/tabbar/mine.png", "iconPath": "static/images/tabbar/mine.png",
"selectedIconPath": "static/images/tabbar/mine_.png", "selectedIconPath": "static/images/tabbar/mine_.png",
"text": "我的" "text": "我的"
} }]
]
}, },
"globalStyle": { "globalStyle": {
"navigationBarTextStyle": "black", "navigationBarTextStyle": "black",

View File

@ -1,8 +1,7 @@
<template> <template>
<view class="normal-login-container"> <view class="normal-login-container">
<view class="logo-content align-center justify-center flex"> <view class="logo-content align-center justify-center flex">
<image style="width: 100rpx;height: 100rpx;" :src="globalConfig.appInfo.logo" mode="widthFix"> <image style="width: 100rpx; height: 100rpx" :src="globalConfig.appInfo.logo" mode="widthFix"></image>
</image>
<text class="title">若依移动端登录</text> <text class="title">若依移动端登录</text>
</view> </view>
<view class="login-form-content"> <view class="login-form-content">
@ -14,7 +13,7 @@
<view class="iconfont icon-password icon"></view> <view class="iconfont icon-password icon"></view>
<input v-model="loginForm.password" type="password" class="input" placeholder="请输入密码" maxlength="20" /> <input v-model="loginForm.password" type="password" class="input" placeholder="请输入密码" maxlength="20" />
</view> </view>
<view class="input-item flex align-center" style="width: 60%;margin: 0px;" v-if="captchaEnabled"> <view class="input-item flex align-center" style="width: 60%; margin: 0px" v-if="captchaEnabled">
<view class="iconfont icon-code icon"></view> <view class="iconfont icon-code icon"></view>
<input v-model="loginForm.code" type="number" class="input" placeholder="请输入验证码" maxlength="4" /> <input v-model="loginForm.code" type="number" class="input" placeholder="请输入验证码" maxlength="4" />
<view class="login-code"> <view class="login-code">
@ -34,98 +33,106 @@
<text @click="handlePrivacy" class="text-blue">隐私协议</text> <text @click="handlePrivacy" class="text-blue">隐私协议</text>
</view> </view>
</view> </view>
</view> </view>
</template> </template>
<script> <script>
import { getCodeImg } from '@/api/login' import { getCodeImg } from '@/api/login';
export default { export default {
data() { data() {
return { return {
codeUrl: "", codeUrl: '',
captchaEnabled: true, captchaEnabled: true,
// //
register: false, register: false,
globalConfig: getApp().globalData.config, globalConfig: getApp().globalData.config,
loginForm: { loginForm: {
username: "admin", username: 'admin',
password: "admin123", password: 'admin123',
code: "", code: '',
uuid: '' uuid: ''
} }
} };
}, },
created() { created() {
this.getCode() this.getCode();
}, },
methods: { methods: {
handleConversion(result) {
// console.log(':', result.initialValue);
// console.log(':', result.newValue);
// console.log(':', result.oldUnit);
// console.log(':', result.newUnit);
},
// //
handleUserRegister() { handleUserRegister() {
this.$tab.redirectTo(`/pages/register`) this.$tab.redirectTo(`/pages/register`);
}, },
// //
handlePrivacy() { handlePrivacy() {
let site = this.globalConfig.appInfo.agreements[0] let site = this.globalConfig.appInfo.agreements[0];
this.$tab.navigateTo(`/pages/common/webview/index?title=${site.title}&url=${site.url}`) this.$tab.navigateTo(`/pages/common/webview/index?title=${site.title}&url=${site.url}`);
}, },
// //
handleUserAgrement() { handleUserAgrement() {
let site = this.globalConfig.appInfo.agreements[1] let site = this.globalConfig.appInfo.agreements[1];
this.$tab.navigateTo(`/pages/common/webview/index?title=${site.title}&url=${site.url}`) this.$tab.navigateTo(`/pages/common/webview/index?title=${site.title}&url=${site.url}`);
}, },
// //
getCode() { getCode() {
getCodeImg().then(res => { getCodeImg().then((res) => {
this.captchaEnabled = res.captchaEnabled === undefined ? true : res.captchaEnabled this.captchaEnabled = res.captchaEnabled === undefined ? true : res.captchaEnabled;
if (this.captchaEnabled) { if (this.captchaEnabled) {
this.codeUrl = 'data:image/gif;base64,' + res.img this.codeUrl = 'data:image/gif;base64,' + res.img;
this.loginForm.uuid = res.uuid this.loginForm.uuid = res.uuid;
} }
}) });
}, },
// //
async handleLogin() { async handleLogin() {
if (this.loginForm.username === "") { if (this.loginForm.username === '') {
this.$modal.msgError("请输入您的账号") this.$modal.msgError('请输入您的账号');
} else if (this.loginForm.password === "") { } else if (this.loginForm.password === '') {
this.$modal.msgError("请输入您的密码") this.$modal.msgError('请输入您的密码');
} else if (this.loginForm.code === "" && this.captchaEnabled) { } else if (this.loginForm.code === '' && this.captchaEnabled) {
this.$modal.msgError("请输入验证码") this.$modal.msgError('请输入验证码');
} else { } else {
this.$modal.loading("登录中,请耐心等待...") this.$modal.loading('登录中,请耐心等待...');
this.pwdLogin() this.pwdLogin();
} }
}, },
// //
async pwdLogin() { async pwdLogin() {
this.$store.dispatch('Login', this.loginForm).then(() => { this.$store
this.$modal.closeLoading() .dispatch('Login', this.loginForm)
this.loginSuccess() .then(() => {
}).catch(() => { this.$modal.closeLoading();
if (this.captchaEnabled) { this.loginSuccess();
this.getCode()
}
}) })
.catch(() => {
if (this.captchaEnabled) {
this.getCode();
}
});
}, },
// //
loginSuccess(result) { loginSuccess(result) {
// //
this.$store.dispatch('GetInfo').then(res => { this.$store.dispatch('GetInfo').then((res) => {
this.$tab.reLaunch('/pages/index') this.$tab.reLaunch('/pages/index');
}) });
}
} }
} }
};
</script> </script>
<style lang="scss"> <style lang="scss">
page { page {
background-color: #ffffff; background-color: #ffffff;
} }
.normal-login-container { .normal-login-container {
width: 100%; width: 100%;
.logo-content { .logo-content {
@ -168,7 +175,6 @@
text-align: left; text-align: left;
padding-left: 15px; padding-left: 15px;
} }
} }
.login-btn { .login-btn {
@ -197,6 +203,5 @@
} }
} }
} }
} }
</style> </style>

View File

@ -1,5 +1,13 @@
<template> <template>
<view class="mine-container" :style="{height: `${windowHeight}px`}"> <view class="mine-container" :style="{ height: `${windowHeight}px` }">
<yjly-number_unit
:unitType="'length'"
:unitName.sync="selectedUnitName"
:value.sync="inputValue"
:showEnglishOnly="true"
:decimalPlaces="5"
@conversion="handleConversion"
></yjly-number_unit>
<!--顶部个人信息栏--> <!--顶部个人信息栏-->
<view class="header-section"> <view class="header-section">
<view class="flex padding justify-between"> <view class="flex padding justify-between">
@ -7,15 +15,10 @@
<view v-if="!avatar" class="cu-avatar xl round bg-white"> <view v-if="!avatar" class="cu-avatar xl round bg-white">
<view class="iconfont icon-people text-gray icon"></view> <view class="iconfont icon-people text-gray icon"></view>
</view> </view>
<image v-if="avatar" @click="handleToAvatar" :src="avatar" class="cu-avatar xl round" mode="widthFix"> <image v-if="avatar" @click="handleToAvatar" :src="avatar" class="cu-avatar xl round" mode="widthFix"></image>
</image> <view v-if="!name" @click="handleToLogin" class="login-tip">点击登录</view>
<view v-if="!name" @click="handleToLogin" class="login-tip">
点击登录
</view>
<view v-if="name" @click="handleToInfo" class="user-info"> <view v-if="name" @click="handleToInfo" class="user-info">
<view class="u_title"> <view class="u_title">用户名{{ name }}</view>
用户名{{ name }}
</view>
</view> </view>
</view> </view>
<view @click="handleToInfo" class="flex align-center"> <view @click="handleToInfo" class="flex align-center">
@ -71,78 +74,86 @@
</view> </view>
</view> </view>
</view> </view>
</view> </view>
</view> </view>
</template> </template>
<script> <script>
import storage from '@/utils/storage' import storage from '@/utils/storage';
export default { export default {
data() { data() {
return { return {
selectedUnitName: 'm(米)',
inputValue: 12,
name: this.$store.state.user.name, name: this.$store.state.user.name,
version: getApp().globalData.config.appInfo.version version: getApp().globalData.config.appInfo.version
} };
}, },
computed: { computed: {
avatar() { avatar() {
return this.$store.state.user.avatar return this.$store.state.user.avatar;
}, },
windowHeight() { windowHeight() {
return uni.getSystemInfoSync().windowHeight - 50 return uni.getSystemInfoSync().windowHeight - 50;
} }
}, },
methods: { methods: {
handleConversion(result) {
// console.log(':', result.initialValue);
// console.log(':', result.newValue);
// console.log(':', result.oldUnit);
// console.log(':', result.newUnit);
},
handleToInfo() { handleToInfo() {
this.$tab.navigateTo('/pages/mine/info/index') this.$tab.navigateTo('/pages/mine/info/index');
}, },
handleToEditInfo() { handleToEditInfo() {
this.$tab.navigateTo('/pages/mine/info/edit') this.$tab.navigateTo('/pages/mine/info/edit');
}, },
handleToSetting() { handleToSetting() {
this.$tab.navigateTo('/pages/mine/setting/index') this.$tab.navigateTo('/pages/mine/setting/index');
}, },
handleToLogin() { handleToLogin() {
this.$tab.reLaunch('/pages/login') this.$tab.reLaunch('/pages/login');
}, },
handleToAvatar() { handleToAvatar() {
this.$tab.navigateTo('/pages/mine/avatar/index') this.$tab.navigateTo('/pages/mine/avatar/index');
}, },
handleLogout() { handleLogout() {
this.$modal.confirm('确定注销并退出系统吗?').then(() => { this.$modal.confirm('确定注销并退出系统吗?').then(() => {
this.$store.dispatch('LogOut').then(() => { this.$store.dispatch('LogOut').then(() => {
this.$tab.reLaunch('/pages/index') this.$tab.reLaunch('/pages/index');
}) });
}) });
}, },
handleHelp() { handleHelp() {
this.$tab.navigateTo('/pages/mine/help/index') this.$tab.navigateTo('/pages/mine/help/index');
}, },
handleAbout() { handleAbout() {
this.$tab.navigateTo('/pages/mine/about/index') this.$tab.navigateTo('/pages/mine/about/index');
}, },
handleJiaoLiuQun() { handleJiaoLiuQun() {
this.$modal.showToast('QQ群133713780') this.$modal.showToast('QQ群133713780、②146013835');
}, },
handleBuilding() { handleBuilding() {
this.$modal.showToast('模块建设中~') this.$modal.showToast('模块建设中~');
}
} }
} }
};
</script> </script>
<style lang="scss"> <style lang="scss">
page { page {
background-color: #f5f6f7; background-color: #f5f6f7;
} }
.mine-container { .mine-container {
width: 100%; width: 100%;
height: 100%; height: 100%;
.header-section { .header-section {
padding: 15px 15px 45px 15px; padding: 15px 15px 45px 15px;
background-color: #3c96f3; background-color: #3c96f3;
@ -194,5 +205,5 @@
} }
} }
} }
} }
</style> </style>

View File

@ -0,0 +1,272 @@
<template>
<view class="unit-converter">
<!-- 数值输入框 -->
<input v-model="inputValue" type="number" @input="handleInputChange" class="input-field" :style="{ width: width + 'px' }" />
<!-- 单位标签 -->
<text @click="toggleUnit" @dblclick="openUnitSelector" class="unit-label" :style="{ color: 'blue' }">
{{ displayUnitName }}
</text>
<!-- 单位选择弹出窗口 -->
<!-- uni-popup 弹窗 -->
<uni-popup ref="unitSelectorPopup" type="bottom" :show="showUnitSelector" @close="onPopupClose">
<view class="unit-selector">
<view v-for="unit in filteredUnitList" :key="unit.id" @click="selectUnit(unit)" class="unit-option">
{{ showEnglishOnly ? unit.unitName.split('(')[0] : unit.unitName }}
</view>
</view>
</uni-popup>
</view>
</template>
<script>
import { listConversion } from '@/api/system/conversion.js';
export default {
props: {
//
unitType: {
type: String,
default: 'length'
},
//
showEnglishOnly: {
type: Boolean,
default: false
},
//
unitName: {
type: String,
required: false,
default: ''
},
//
value: {
type: Number,
required: true
},
//
decimalPlaces: {
type: Number,
default: 2
},
width: {
type: Number,
required: false,
default: 80
}
},
data() {
return {
inputValue: this.value, //
currentUnit: null, //
unitList: [], //
showUnitSelector: false //
};
},
onLoad() {
//
uni.$on('globalClick', this.handleClickOutside);
},
onUnload() {
//
uni.$off('globalClick', this.handleClickOutside);
},
computed: {
//
displayUnitName() {
if (!this.currentUnit) return '';
return this.showEnglishOnly ? this.currentUnit.unitName.split('(')[0] : this.currentUnit.unitName;
},
//
filteredUnitList() {
return this.unitList.filter((unit) => unit.unitName !== this.currentUnit?.unitName);
}
},
watch: {
// unitType
unitType: {
immediate: true,
handler(newVal) {
this.loadUnitList(newVal);
}
},
// unitName
unitName: {
immediate: true,
handler(newVal) {
console.log(newVal);
this.currentUnit = this.unitList.find((unit) => unit.unitName == newVal);
}
},
// value
value: {
immediate: true,
handler(newVal) {
this.inputValue = newVal;
}
}
},
methods: {
//
handleClickOutside(event) {
if (this.$refs.unitSelector && !this.$refs.unitSelector.contains(event.target)) {
this.showUnitSelector = false;
}
},
//
toggleUnitSelector() {
this.showUnitSelector = !this.showUnitSelector;
},
//
async loadUnitList(unitType) {
try {
const response = await listConversion({ pageSize: 100, unitType: unitType });
console.log(response);
this.unitList = response.rows;
if (this.unitName == '') {
//
this.currentUnit = this.unitList.find((unit) => unit.baseUnit == 1);
console.log(this.currentUnit);
} else {
this.currentUnit = this.unitList.find((unit) => unit.unitName == this.unitName);
console.log(this.currentUnit);
if (this.currentUnit === undefined) {
this.currentUnit = this.unitList.find((unit) => unit.baseUnit === 1);
}
}
} catch (error) {
console.error('Failed to load unit list:', error);
}
},
//
handleInputChange() {
this.$emit('input', this.inputValue); //
this.convertAndEmit();
},
//
toggleUnit() {
const currentIndex = this.unitList.indexOf(this.currentUnit);
const nextIndex = (currentIndex + 1) % this.unitList.length;
let oldUnit = this.currentUnit;
let newUnit = this.unitList[nextIndex];
this.currentUnit = newUnit;
// console.log('', currentIndex, nextIndex, this.currentUnit);
this.convertAndEmit(oldUnit, newUnit);
},
//
openUnitSelector() {
this.showUnitSelector = true;
},
//
selectUnit(unit) {
console.log('所选择的单位', unit);
let oldUnit = this.currentUnit;
let newUnit = unit;
this.currentUnit = unit;
this.showUnitSelector = false;
this.convertAndEmit(oldUnit, newUnit);
},
//
convertAndEmit(oldUnit, newUnit) {
if (!newUnit) return;
//
const baseUnit = this.unitList.find((unit) => unit.baseUnit === 1);
if (!baseUnit) return;
//
const baseValue = this.inputValue / oldUnit.conversionFactor;
//
const newValue = baseValue * newUnit.conversionFactor;
console.log('转换值', newUnit.unitName, this.inputValue, baseValue, newValue);
let roundedValue;
if (newUnit.unitName === 'ly(光年)') {
// 使
roundedValue = newValue.toExponential();
} else {
roundedValue = this.roundToDecimalPlaces(newValue);
}
//
this.$emit('conversion', {
initialValue: this.inputValue,
newValue: roundedValue,
oldUnit: oldUnit.unitName,
newUnit: newUnit.unitName
});
this.inputValue = parseFloat(roundedValue);
// unitName
this.$emit('update:unitName', this.currentUnit.unitName);
},
//
// conversionFactor
roundToDecimalPlaces(value) {
const multiplier = Math.pow(10, this.decimalPlaces);
const val = value * multiplier;
const intVal = Math.trunc(val);
const decimalPart = val - intVal;
if (decimalPart < 0.5) {
return intVal / multiplier;
} else if (decimalPart > 0.5) {
return (intVal + 1) / multiplier;
} else {
return intVal % 2 === 0 ? intVal / multiplier : (intVal + 1) / multiplier;
}
}
}
};
</script>
<style scoped>
.unit-converter {
display: flex;
align-items: center;
gap: 10px;
position: relative;
}
.input-field {
padding: 2px;
border: 1px solid #ccc;
border-radius: 4px;
font-size: 14px;
}
.unit-label {
cursor: pointer;
font-weight: bold;
font-size: 12px;
}
.unit-selector {
/* 设置容器的最大高度,当内容超出这个高度时会出现滚动条 */
max-height: 200px;
/* 超出内容时显示纵向滚动条 */
overflow-y: auto;
/* 横向内容不溢出,隐藏多余部分 */
overflow-x: hidden;
/* 其他样式保持不变 */
position: absolute;
z-index: 1000;
background-color: white;
border: 1px solid #ccc;
border-radius: 4px;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
padding: 2px 0;
min-width: 100px;
list-style-type: none;
margin: 0;
}
.unit-option {
padding: 2px 10px;
cursor: pointer;
font-size: 14px;
}
.unit-option:hover {
background-color: #f0f0f0;
}
</style>

View File

@ -0,0 +1,83 @@
{
"id": "yjly-number_unit",
"displayName": "yjly-number_unit",
"version": "1.0.0",
"description": "yjly-number_unit",
"keywords": [
"yjly-number_unit"
],
"repository": "",
"engines": {
"HBuilderX": "^3.1.0"
},
"dcloudext": {
"type": "component-vue",
"sale": {
"regular": {
"price": "0.00"
},
"sourcecode": {
"price": "0.00"
}
},
"contact": {
"qq": ""
},
"declaration": {
"ads": "",
"data": "",
"permissions": ""
},
"npmurl": ""
},
"uni_modules": {
"dependencies": [],
"encrypt": [],
"platforms": {
"cloud": {
"tcb": "u",
"aliyun": "u",
"alipay": "u"
},
"client": {
"Vue": {
"vue2": "u",
"vue3": "u"
},
"App": {
"app-vue": "u",
"app-nvue": "u",
"app-uvue": "u"
},
"H5-mobile": {
"Safari": "u",
"Android Browser": "u",
"微信浏览器(Android)": "u",
"QQ浏览器(Android)": "u"
},
"H5-pc": {
"Chrome": "u",
"IE": "u",
"Edge": "u",
"Firefox": "u",
"Safari": "u"
},
"小程序": {
"微信": "u",
"阿里": "u",
"百度": "u",
"字节跳动": "u",
"QQ": "u",
"钉钉": "u",
"快手": "u",
"飞书": "u",
"京东": "u"
},
"快应用": {
"华为": "u",
"联盟": "u"
}
}
}
}
}

View File

@ -0,0 +1 @@
# yjly-number_unit