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>



Logo

前往低代码交流专区

更多推荐