信号强度
需求
vue项目,需要实时监控系统信号,要求:
1.共五格信号;
2.信号0-100为满值,信号100-500为四格,信号500-1000为三格,信号1000-5000为两格,信号5000-20000为一格,大于20000为无信号;
3.信号0-100为绿色,信号100-500为绿色,信号500-1000为黄色,信号1000-5000为黄色,信号5000-20000为红色,大于20000为灰色。
效果
图标地址
免费 信号图标-六个图标-图标资源
https://download.csdn.net/download/xuelong5201314/88701607
代码
signalStrength.vue 文件
<!-- 信号强度 -->
<template>
<div class="signal-strength">
<img v-if="strength === 5" :src="url5" />
<img v-else-if="strength === 4" :src="url4" />
<img v-else-if="strength === 3" :src="url3" />
<img v-else-if="strength === 2" :src="url2" />
<img v-else-if="strength === 1" :src="url1" />
<img v-else :src="url0" />
</div>
</template>
<script>
export default {
name: 'SignalStrength',
props: {
// 信号强度,默认满格信号
strength: {
type: Number,
default: 5,
validator: function (value) {
// 必须为不大于5的整数
if (value > 5 || value < 0) {
return false
} else {
return true
}
}
}
},
data() {
return {
url0: require('@/assets/image/signal-0.png'),
url1: require('@/assets/image/signal-1.png'),
url2: require('@/assets/image/signal-2.png'),
url3: require('@/assets/image/signal-3.png'),
url4: require('@/assets/image/signal-4.png'),
url5: require('@/assets/image/signal-5.png')
}
}
}
</script>
<style lang="scss" scoped>
.signal-strength {
width: 16px;
height: 16px;
position: absolute;
top: 6px;
left: 50%;
transform: translate(-50%, -50%);
img {
-webkit-user-drag: none;
user-select: none;
}
}
</style>
index.vue 父组件
<template>
<div class="content-piece">
<div class="content-item-two">
网络延迟:
<span v-if="systemSignal > 0">{{ systemSignal }}ms</span> <span v-else>无信号</span>
网络信号:
<div class="signal-box">
<signal-strength :strength="systemSignalNum"></signal-strength>
</div>
</div>
</div>
</template>
<script>
import signalStrength from './signalStrength.vue'
import api from './api'
export default {
components: {
signalStrength
},
data() {
return {
systemSignal: 0, // 系统信号
systemSignalNum: 0 // 系统信号栏
}
},
created() {
this.getSignal()
},
beforeDestroy() {
// 销毁定时器
clearInterval(this.timer)
},
methods: {
// 获取系统信号延迟
getSystemSignal() {
const time = new Date().getTime()
// 当前请求没有返回值,通过计算请求成功后的时间与发送请求前的时间之差获取当前信号
api.getSystem().then(res => {
const delay = new Date().getTime() - time
this.systemSignal = delay
this.systemSignalNum = this.calculateSignal(delay)
}).catch(() => {
this.systemSignal = -1 // 系统信号
this.systemSignalNum = 0 // 系统信号栏
})
},
// 获取信号延迟
getSignal() {
this.getSystemSignal()
this.timer = setInterval(() => {
this.getSystemSignal()
}, 3000)
},
// 计算信号
calculateSignal(num) {
let signalValue = 0
if (num <= 100 && num > 0) {
signalValue = 5
} else if (num > 100 && num <= 500) {
signalValue = 4
} else if (num > 500 && num <= 1000) {
signalValue = 3
} else if (num > 1000 && num <= 5000) {
signalValue = 2
} else if (num > 5000 && num <= 20000) {
signalValue = 1
} else {
signalValue = 0
}
return signalValue
}
}
}
</script>