1.使用方式
1.1第一步
//main.js文件中
import Vue from "vue";
//下方全部代码在这个文件中
import foucs from "./foucs.js"
//全局注入文件,方便在各个功能中直接使用
Vue.mixin(foucs )
1.2,功能引用方式
<template>
<view class="top-search-item">
<input style="margin: 0 10rpx;" placeholder="请扫描或输入单号"
fontSize="12" v-model="searchData.a" :focus="foucsIndex == 0">
</input>
<input style="margin: 0 10rpx;" placeholder="请扫描或输入单号"
fontSize="12" v-model="searchData.b" :focus="foucsIndex == 1">
</input>
<!-- 光标即可聚焦到第二个input上 -->
<button @click="$toFoucs(1)">按钮</button>
</view>
</template>
<script>
export default {
name: "demo",
data() {
return {
searchData: {
a: "",
b: ""
},
};
},
};
</script>
引入的focus.js文件,代码如下
//focus.js
/**
* @description 用于各个功能中,光标聚焦到指定input上
* 用法如下:
* <input :focus="foucsIndex == 1" />
* 调用 $toFoucs(1) 光标即可聚焦到该input上
* @author bing
* @date 2023-08-04 15:58
*/
export default {
data() {
return {
foucsIndex: 0,
}
},
methods: {
/**
* @description 定位光标到指定input框
* @author bing
* @date 2023-08-04 17:16
* @param {Number} to 要定位到的input,
* @param {Function} callback 定位之后的回调
* @param {boolean} hideKeyboard 是否关闭软键盘,默认关闭
*/
$toFoucs(to, hideKeyboard = true, callback, ) {
this.foucsIndex = 9999;
this.$nextTick(() => {
this.foucsIndex = to;
hideKeyboard ? this.$hideKeyboard() : ""
callback ? callback() : ''
})
},
// 关闭软键盘,防冻
$hideKeyboard() {
var interval = setInterval(function() {
uni.hideKeyboard(); //隐藏软键盘
}, 10);
setTimeout(() => {
clearInterval(interval);
}, 1000);
}
}
}