vue中的侦听器watch的使用,watch和computed的区别

watch侦听器的作用就是侦听一个data中的值的变化,变化后可以写一个方法,让其进行一些操作(业务逻辑的编写)。

侦听器watch和计算属性computed的区别

  1. 计算属性computed必须要返回一个值,而且在页面渲染的同时就会执行里边的业务逻辑,也就是会先执行一遍你写的业务逻辑,                                   
  2. watch只有发生变化时才会执行,也就是说值没有变化,它是不执行里边业务逻辑的。
  3. watch监听的是一个变量的变化,只有变量变化时才执行
  4. computed是返回一个数据,这个数据可以依赖多个变量,只要依赖的其中一个变量发生变化,就会重新计算。
  5. 计算属性的代码更加简洁
现在总结一下method、watch和computed三者如果都能实现相同的功能,它们之间的取舍和使用优先级。
  • computed 和  method都能实现的功能,建议使用computed,因为有缓存,不用渲染页面就刷新。
  • computed 和  watch 都能实现的功能,建议使用 computed,因为更加简洁。

代码:

<template>
<!-- vue中的侦听器(watch的使用) -->
    <div class="base05">
        <home-back></home-back>
        <div>总数:{
    
    {total}}</div>
        <div>总数:{
    
    {newTotal}}</div>
        <button @click="count++">增加count</button>
    </div>
</template>

<script>
import Back from "@/components/common/back.vue"
export default {
    data(){
        return{
            count:1,
            price:10,
            newTotal:''
        }
    },
    components:{
        'home-back':Back
    },
    watch:{
        count(now,pre){ 
            console.log(now)
            console.log(pre)
            return this.newTotal = this.price*this.count
        }
    },
    computed:{
        total(){
            return this.count * this.price
        },
    },
    methods:{
    }
}
</script>

<style scoped lang="stylus">
    .base04
        margin-top 30px
        margin-left 50px
        h2
            margin-top 20px
</style>

猜你喜欢

转载自blog.csdn.net/yangdl6/article/details/119459776