console
let tid = null
const InputSize = Vue.component('InputSize', {
template: `<div>
<input v-model="inputValue"/>
<select v-model="selectValue">
<option v-for="(item, index) in options" :value="item.value" :key="item.value">{{item.label}}</option>
</select>
</div>`,
data: function () {
return {
options: [
{
value: 1,
label: 'B'
},
{
value: 1024,
label: 'KB'
},
{
value: 1024 * 1024,
label: 'MB'
},
{
value: 1024 * 1024 * 1024,
label: 'GB'
},
{
value: 1024 * 1024 * 1024 * 1024,
label: 'TB'
},
],
inputValue: '',
selectValue: 1
}
},
watch: {
inputValue(v) {
this.formatSelect()
}
},
methods: {
formatSelect() {
if (tid) {
clearTimeout(tid)
}
tid = setTimeout(() => {
console.log(this.inputValue)
if (!this.inputValue) {
return
}
const currentBV = this.inputValue * this.selectValue
const len = this.options.length
if (currentBV >= this.options[len - 1].value) {
const res = (currentBV / this.options[len - 1].value).toFixed(2)
this.inputValue = res
this.selectValue = this.options[len - 1].value
return
}
for (let i = 0; i < len; i++) {
if ((currentBV < this.options[i].value)) {
const res = (currentBV / this.options[i - 1].value).toFixed(2)
console.log(res, i)
this.inputValue = res
this.selectValue = this.options[i - 1].value
break
}
}
}, 1000)
}
}
})
const app = new Vue({
el: '#app',
components: { InputSize },
template: `
<InputSize @change="change"></InputSize>`,
methods: {
change(vavlue) {
console.log(vavlue)
}
}
})
<div id="app"></div>