computed的get属性
html:
<template> <div class="input-text"> <input type="text" v-model='firstName'> <input type="text" v-model='lastName'> {{fullName}} </div> </template>
js:
<script> export default { components: { }, ready: function() { }, methods: { }, data() { return { firstName: 'Foo', lastName: 'Bar' } }, computed: { fullName: { // getter get: function() { return this.firstName + ' and ' + this.lastName }, // setter set: function(newValue) { var names = newValue.split(' and ') 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='a'>{{b}} <input type="button" value="修改b的值" @click='updateData'> <input type="text" v-model='c'> </div> </template>
js:
<script> export default { components: { }, ready: function() { }, methods: { updateData:function(){ this.b=this.b;//给 b 重新赋值时就会调用 b 的 set 属性,从而改变 c 的值 } }, data() { return { a:'1:30', c:'' } }, computed: { b:{ get: function() {//通过a的值改变b的值 var time=this.a; time = time ? time.split(':') : ''; 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 + ''; hoursTime = hoursTime + ''; hoursTime = hoursTime ? hoursTime.split('.') : ''; this.c = hoursTime[0] + ':' + minutesTime; console.log(hoursTime[0] + ':' + minutesTime); } } } } </script>