在 Vue.js 裡,常常使用 computed 讓我們就既有的值做進一步的轉換,下面這段就是把輸入的文字變成反向的字(天能是你?)
<div id="app">
<input type="text" v-model="message">
<h1>{{message}}</h1>
<h1>{{reversedMessage}}</h1>
</div>
這樣在 reversedMessage 那邊我們就可以看到即時輸入的文字變成反向了。
data: {
message: "Hello, Vue."
},
computed:{
reversedMessage: function(){
let reversed=this.message.split('').reverse().join('')
return reversed;
}
}
利用這個,我們可以在使用者輸入姓跟名的時候幫他拚出全名:
<div id="app">
Enter your <input type="text" v-model="firstName" placeholder="first name">
<input type="text" v-model="lastName" placeholder="last name">
<hr>
Hello, {{fullName}}
</div>
data: {
firstName: "",
lastName: ""
},
computed:{
fullName: function(){
return this.firstName+" "+this.lastName;
}
}
比較一下跟 watch 的差別,watch 必須要是監測既有的值,而 computed 則是把當下的值直接作轉換。
data: {
firstName: "",
lastName: "",
fullName: ""
},
watch:{
firstName: function(val){
this.fullName=val+" "+this.lastName;
},
lastName: function(val){
this.fullName=this.firstName+" "+val;
}
}
computed 預設是依據某個值後做變化,如果我們想改變 computed 的值,也可以藉由 set 把值給回推回去:
Enter your <input type="text" v-model="firstName" placeholder="first name">
<input type="text" v-model="lastName" placeholder="last name">
Hello, <input type="text" v-model="fullName">
data: {
firstName: "Tom",
lastName: "Hanks"
},
computed:{
fullName:{
get: function(){
return this.firstName+" "+this.lastName;
},
set: function(newValue){
var name = newValue.split(' ');
this.firstName = name[0];
this.lastName = name[name.length - 1];
}
}
}
這邊就是我們在 vue 裡的 computed 的應用。