Rumah >hujung hadapan web >tutorial js >Vue.js计算属性computed

Vue.js计算属性computed

高洛峰
高洛峰asal
2016-12-03 09:11:381225semak imbas

computed的get属性

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和set属性:

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>


Kenyataan:
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn