Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.
Vue2.x computed attributes:
Vue computed attributes
- Is a function that uses its return value
- You can also do setter,getter binding in both directions
Bidirectional binding value palette 1,2
Bidirectional binding value palette method 1
Bidirectional binding value palette implementation code and comments for each step
<div id="box">
<input type="text" v-model="color" /> {{ color }}
<div id="colorBox" :style="{'background': color}">Third Party</div>
</div>
Copy the code
<script>
new Vue({
el: '#box'.data: {
r: ' '.g: ' '.b: ' ',},computed: {
color: {
get(){
return `rgb(The ${this.r}.The ${this.g}.The ${this.b}) `
},
set(value) {
var colorStr = value.substring(4, v.length-1)
var colorArr = colorStr.split(",")
this.r = colorArr[0]
this.g = colorArr[1]
this.b = colorArr[2]
}
}
},
})
</script>
Copy the code
Bidirectional binding value palette method 2
Bidirectional binding value palette implementation code and comments for each step
<div id="box">
<input type="text" v-model="color" /> {{ color }}
<div id="colorBox" :style="{'background': getColor}">Third Party</div>
</div>
Copy the code
<script>
new Vue({
el: '#box'.data: {
r: ' '.g: ' '.b: ' ',},computed: {
color: {
get(){
return `The ${this.r}.The ${this.g}.The ${this.b}`
},
set(value) {
var colorStr = value.split(/\s+/)
this.r = Math.min(colorArr[0].255)
this.g = Math.min(colorArr[1].255)
this.b = Math.min(colorArr[2].255)}},getColor(){
return `rgb(The ${this.r}.The ${this.g}.The ${this.b}) `
}
},
})
</script>
Copy the code
Above, the value of the sugar binding input box is displayed through v-Model syntax, and the corresponding value is computed automatically through computed attributes computed computed.
Over a long period of time, a big goal is divided into many small goals to complete step by step, no hard bones can not chew! Classmates come on together!!
Learn about dynamic components below
<component :is= "Component name" ></component>
Dynamic components
Exercise: Tab Tab