v-model演示十六进制颜色值的变化

177 阅读1分钟

最近学习Vue,学到计算属性的时候,遇到一个案例,使用计算属性得到颜色值。我们知道,在前端中,颜色使用6位的十六进制数来表示,2位表示红色R,2位表示绿色G,2位表示蓝色B,下面代码生成的网页特别适合用来演示颜色值的变化。 使用v-model改变并获得红、绿、蓝三种颜色值,使用计算属性得到最终的颜色值,并动态绑定设置为div的背景色。

image.png

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<meta name="viewport" content="width=device-width, initial-scale=1.0">
		<meta http-equiv="X-UA-Compatible" content="ie=edge">
		<title>使用计算属性得到颜色值</title>
		<style>
			.box {
				width: 200px;
				height: 200px;
				border: 1px solid #ccc;
			}
		</style>
	</head>
	<body>
		<div id="app">
			<div>
				<span>R:</span> <input type="range" min='0' max='255' v-model.number="r">
			</div>
			<div>
				<span>G:</span> <input type="range" min='0' max='255' v-model.number="g">
			</div>
			<div>
				<span>B:</span> <input type="range" min='0' max='255' v-model.number="b">
			</div>
			<hr>
			<h2> 颜色值:{{ rgb }}</h2>
			<div class="box" :style="{ backgroundColor: rgb }">
			</div>
		</div>
		<script src="./lib/vue.js"></script>
		<script>
			var vm = new Vue({
				el: '#app',
				data: {
					r: 0,
					g: 0,
					b: 0
				},
				computed: {
					rgb() {
						RR = this.r.toString(16)
						RR = this.r < 16 ? '0' + RR : RR
						GG = this.g.toString(16)
						GG = this.g < 16 ? '0' + GG : GG
						BB = this.b.toString(16)
						BB = this.b < 16 ? '0' + BB : BB
						return '#' + RR + GG + BB
					}
				},
			});
		</script>
	</body>

</html>

``

``