computed擅長處理的場景:一個資料受多個資料影響
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="https://cdn.jsdelivr.net/npm/vue"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
</head>
<body>
<div id="app">
<input v-model="firstName" type="text" name="" id="input" class="form-control" value="" required="required" pattern="" title="">
<input v-model="lastName" type="text" name="" id="input" class="form-control" value="" required="required" pattern="" title="">
<input v-model="fullName" type="text" name="" id="input" class="form-control" value="" required="required" pattern="" title="">
<input v-model="full2Name" type="text" name="" id="input" class="form-control" value="" required="required" pattern="" title="">
</div>
<script>
var vm=new Vue({
el:'#app',
data:{
firstName: "",
lastName: '',
full2Name:""
},
methods:{},
// 對於任何複雜邏輯,你都應當使用計算屬性
computed: {
fullName(){
return this.firstName + this.lastName
}
},
watch: {
firstName(){
this.full2Name = this.firstName + this.lastName
},
lastName(){
this.full2Name = this.firstName + this.lastName
}
},
});
Vue.config.devtools = true
</script>
</body>
</html>