Home  >  Article  >  Web Front-end  >  Vue.js computed property computed

Vue.js computed property computed

高洛峰
高洛峰Original
2016-12-03 09:11:381150browse

computed get attributes

html:

<template>
 <div class="input-text">
 <input type="text" v-model=&#39;firstName&#39;>
 <input type="text" v-model=&#39;lastName&#39;>
 {{fullName}}
 </div>
</template>

js:

<script>
export default {
 components: {
 
 },
 ready: function() {
 
 },
 methods: {
 },
 data() {
 return {
 firstName: &#39;Foo&#39;,
 lastName: &#39;Bar&#39;
 }
 },
 computed: {
 fullName: {
 // getter
 get: function() {
 return this.firstName + &#39; and &#39; + this.lastName
 },
 // setter
 set: function(newValue) {
 var names = newValue.split(&#39; and &#39;)
 this.firstName = names[0]
 this.lastName = names[names.length - 1]
 }
 }
 }
}
</script>

computed get and set attributes:

html:

<template>
 <div class="input-text">
 <input type="text" v-model=&#39;a&#39;>{{b}}
 <input type="button" value="修改b的值" @click=&#39;updateData&#39;>
 <input type="text" v-model=&#39;c&#39;>
 </div>
</template>

js:

<script>
export default {
 components: {
 },
 ready: function() {
 },
 methods: {
 updateData:function(){
 this.b=this.b;//给 b 重新赋值时就会调用 b 的 set 属性,从而改变 c 的值
 }
 },
 data() {
 return {
 a:&#39;1:30&#39;,
 c:&#39;&#39;
 }
 },
 computed: {
 b:{
 get: function() {//通过a的值改变b的值
 var time=this.a;
 time = time ? time.split(&#39;:&#39;) : &#39;&#39;;
 let hours = time[0];
 let minutes = time[time.length - 1];
 return parseInt(hours) * 60 + parseInt(minutes);
 },
 set:function(newValue){//通过b值的改变,设置 c 的值
 let newTimes = newValue;
 let hoursTime = parseInt(newTimes) / 60;
 let minutesTime = parseInt(newTimes) % 60;
 newTimes = newTimes + &#39;&#39;;
 hoursTime = hoursTime + &#39;&#39;;
 hoursTime = hoursTime ? hoursTime.split(&#39;.&#39;) : &#39;&#39;;
 this.c = hoursTime[0] + &#39;:&#39; + minutesTime;
 console.log(hoursTime[0] + &#39;:&#39; + minutesTime);
 }
 }
 }
}
</script>


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn