Vue.js學習(二):computed響應數據變化與其他幾種方法的比較

vue重methods、computed、watch以及v-model都能偵聽數據,並相應數據的變化

1)methods:每次獲取都會重新計算求值

    <div id="app">
        <label for="firstName">First Name:</label>
        <input type="text" id="firstName" v-model="first" @keypress="change">
        <label for="lastName">Last Name:</label>
        <input type="text" id="lastName" v-model="last" @keypress="change">

        <h2>methods: {{name}}</h2>
    </div>

let vm=new Vue({
    el:'#app',
    data:{
        price: 1
    },
    methods:{
        change(){
            this.price
        }
    }
})

2)computed:基於數據依賴進行緩存,只有當數據變化時,纔會重新求值;

    <div id="app">
        <label for="firstName">First Name:</label>
        <input type="text" id="firstName" v-model="first">
        <label for="lastName">Last Name:</label>
        <input type="text" id="lastName" v-model="last">

        <h2>computed: {{cap}}</h2>
    </div>
let vm=new Vue({
    el:'#app',
    data:{
        first:'',
        last: "",
        name:""
    },
    computed:{
        cap:function(){
            return this.first+" "+this.last
        }
    }
})

3)watch:當需要在數據變化時執行異步或者開銷較大的操作時,這個方式最有用;

    <div id="app">
        <label for="firstName">First Name:</label>
        <input type="text" id="firstName" v-model="first">
        <label for="lastName">Last Name:</label>
        <input type="text" id="lastName" v-model="last">

        <h2>watch: {{cap}}</h2>
    </div>

let vm=new Vue({
    el:'#app',
    data:{
        first:'',
        last: "",
        name:""
    },
    watch:{
        first(value){
            this.name=value+' '+this.last
        },
        last(value){
            this.name=this.first+" "+value
        }
    }
})

4)v-model:這是基於數據雙向綁定的

    <div id="app">
        <label for="firstName">First Name:</label>
        <input type="text" id="firstName" v-model="first">
        <label for="lastName">Last Name:</label>
        <input type="text" id="lastName" v-model="last">

        <h2>v-model:{{first+' '+last}}</h2> 
    </div>



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章