有用的小函数:计算文本DOM渲染到页面的宽度、在Vue中获取客户端ip、el-input-number限制输入字符长度

本文用作个人备份,记录一些有用的小函数

计算文本DOM渲染到页面的实际宽度

function getTextWidth(text, fontSize) {const span = document.createElement("span");span.style.display = "inline-block";span.style.width = "auto";span.style.whiteSpace = "nowrap";span.style.fontSize = fontSize;span.textContent = text;document.body.appendChild(span);const width = span.offsetWidth;document.body.removeChild(span);return width;
}

在Vue中获取客户端ip

methods:{ipCallback(data){// ...这里写处理逻辑}
},mounted() {// 利用jsonp向外部接口获取客户端的外网ip地址const script = document.createElement("script");script.src = "https://api.ipify.org?format=jsonp&callback=ipCallback";// 因为jsonp是通过script标签的src属性来请求数据的,所以需要将回调函数挂载到window上window.ipCallback = this.ipCallback.bind(this);document.body.appendChild(script);
},

el-input-number限制输入字符长度

<el-input-numberv-model.number="formData.num":min="0":max="9999999999":step="1"@change="handleChange"
>el-input-number>
// 当输入变更,限制10位字符长度,截断超出部分
handleChange(val) {if (val && val.toString().length > 10) {this.$nextTick(() => {this.formData.num = Number(val.toString().slice(0, 10));});}
},

滑动式地交换数组中两个元素的位置

Example

描述:将下标为0的元素拖动到下标为2的位置
startIndex: 0
endIndex: 2
source: [0, 1, 2, 3, 4, 5]
target: [1, 2, 0, 3, 4, 5]

实现

movingSwap(source, startIndex, endIndex) {const target = JSON.parse(JSON.stringify(source));return target.splice(endIndex, 0, ...target.splice(startIndex, 1));
},

难点拆解

  1. 执行target.splice(startIndex, 1)splice函数的返回值是被删除的元素的数组,这里就是[0],splice函数是有副作用的,此时target变成了[1, 2, 3, 4, 5]
  2. 那么此时只需要在endIndex的位置插入处于startIndex的值,就是target.splice(endIndex, 0, ...target.splice(startIndex, 1))
  3. 在此例中就是[1, 2, 3, 4, 5].splice(2, 0, ...[0]),结果就是[1, 2, 0, 3, 4, 5]

Vue中重置element表单数据和状态

在一些弹窗显隐的时候经常要做这样的重置操作,这里就封装成一个小方法了

//重置表单,formRef为表单的ref值,excludeFields是不需要重置的字段
Vue.prototype.$reset = function (formRef, ...excludeFields) {this.$refs[formRef]?.resetFields();const thisData = this.$data;const initialData = this.$options.data.call(this);if (!excludeFields || excludeFields.length === 0) {excludeFields = [];}for (const attrName in thisData) {if (excludeFields && excludeFields.includes(attrName)) {continue;}thisData[attrName] = initialData[attrName];}this.$nextTick(() => {this.$refs[formRef]?.clearValidate();});
};


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部