1 计算属性及其特点
2 使用计算属性改造案例
2-1案例-原版
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Documenttitle>
<style>
.box {
width: 200px;
height: 200px;
border: 1px solid #ccc;
}
style>
head>
<body>
<div id="app">
<div>
<span>R:span>
<input type="text" v-model.number="r">
div>
<div>
<span>G:span>
<input type="text" v-model.number="g">
div>
<div>
<span>B:span>
<input type="text" v-model.number="b">
div>
<hr>
<div class="box" :style="{ backgroundColor: `rgb(${r}, ${g}, ${b})` }">
{{ `rgb(${r}, ${g}, ${b})` }}
div>
<button @click="show">按钮button>
div>
<script src="./lib/vue-2.6.12.js">script>
<script>
// 创建 Vue 实例,得到 ViewModel
var vm = new Vue({
el: '#app',
data: {
// 红色
r: 0,
// 绿色
g: 0,
// 蓝色
b: 0
},
methods: {
// 点击按钮,在终端显示最新的颜色
show() {
console.log(`rgb(${this.r}, ${this.g}, ${this.b})`)
}
},
});
script>
body>
html>
2-2案例-计算属性改造版
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Documenttitle>
<style>
.box {
width: 200px;
height: 200px;
border: 1px solid #ccc;
}
style>
head>
<body>
<div id="app">
<div>
<span>R:span>
<input type="text" v-model.number="r">
div>
<div>
<span>G:span>
<input type="text" v-model.number="g">
div>
<div>
<span>B:span>
<input type="text" v-model.number="b">
div>
<hr>
<div class="box" :style="{ backgroundColor: rgb }">
{{ rgb }}
div>
<button @click="show">按钮button>
div>
<script src="./lib/vue-2.6.12.js">script>
<script>
// 创建 Vue 实例,得到 ViewModel
var vm = new Vue({
el: '#app',
data: {
// 红色
r: 0,
// 绿色
g: 0,
// 蓝色
b: 0
},
methods: {
// 点击按钮,在终端显示最新的颜色
show() {
console.log(this.rgb)
}
},
// 所有的计算属性,都要定义到 computed 节点之下,且计算属性要被定义成“方法格式”
computed: {
// rgb 作为一个计算属性,被定义成了方法格式
// 这个方法要返回一个生成好的字符串"rgb(x,x,x)"
rgb(){
return `rgb(${this.r},${this.g},${this.b})` //this表示vm
}
}
});
console.log(vm)
script>
body>
html>
3 总结-计算属性