首页 > 其他分享 >09watch(监视属性)对比computed(计算属性)

09watch(监视属性)对比computed(计算属性)

时间:2022-12-03 18:11:33浏览次数:32  
标签:Vue computed watch 09watch fullName 对比 属性

一、监视属性 与 计算属性 普通实现对比

image

二、监视属性 与 计算属性 异步实现对比

image

三、对比

computed和watch之间的对比:

1.computed能完成的给你,watch都能完成;
2.watch能完成的功能,computed不一定能完成,例如:watch能完成异步操作。

两个重要小原则:

1.被Vue管理的函数,最好写成普通函数。这样this的指向才是vm或者 组件实例对象。
2.所有不被Vue管理的函数(定时器的回调函数,Ajax的回调函数等),最好写成箭头函数,
这样this的指向才是vm 或 组件实例对象。

四、Vue代码实现——异步刷新


<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>watch(监视属性)对比computed(计算属性)</title>
    <script type="text/javascript" src="../js/vue.js"></script>
</head>
<body>
    <!--
        computed和watch之间的对比:
            1.computed能完成的给你,watch都能完成;
            2.watch能完成的功能,computed不一定能完成,例如:watch能完成异步操作。
        两个重要小原则:
            1.被Vue管理的函数,最好写成普通函数。这样this的指向才是vm或者 组件实例对象。
            2.所有不被Vue管理的函数(定时器的回调函数,Ajax的回调函数等),最好写成箭头函数,
            这样this的指向才是vm 或 组件实例对象。
    -->
    <div id="root">
        姓:<input type="text" v-model="firstName"><br/><br/>
        名:<input type="text" v-model="lastName"><br/><br/>
        测试:<input type="text"><br/><br/>
        全名:<span>{{fullName}}</span><br/><br/>
    </div>
</body>
<script type="text/javascript">
    Vue.config.productionTip = false //阻止vue 在启动时生成生产提示
   
    const vm =new Vue({
        el:root,
        data:{
            firstName:'张',
            lastName:'三',
            fullName:'张-三'
        },
        watch:{
            firstName(newValue){
                //姓名被修改后,等1秒钟,再刷新fullName的值
                setTimeout(() =>{
                    console.log(this)  //Vue
                    this.fullName = newValue+'-'+this.lastName
                },1000)
            },
            lastName(newValue){
                this.fullName = this.firstName+'-'+newValue
            }
        }
    })
</script>
</html>


标签:Vue,computed,watch,09watch,fullName,对比,属性
From: https://www.cnblogs.com/quliangshyang/p/16948498.html

相关文章