vue中wahch和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">
    <script type="text/javascript" src="../js/vue.js"></script>

    <title>监视属性5姓名案例_watch实现.</title>
</head>
<body>
    <!-- 
        computed和watch之间的区别
        1.computed能完成的,watch一定能完成
        两个重要原则
        所有被vue管理的函数最好都写成普通函数,这样this才能指向vue或者组件实例对象
        所有不被vue管理的函数,如ajax的回调函数,定时器函数等,最好写成箭头函数,这样this才能指向vue或者vue的组件实例对象


     -->
    <div id="root"><input type="text" v-model="firstNam" ><br><input type="text" v-model="lastName"><br>
       全名 <span>{{fullName}}</span>
    </div>
    <script>
        const vm=new Vue({
            el: "#root",
            data: {
                firstNam: "",
                lastName:"",
                fullName:'张-三'
            },
            computed:{
               /*  fullName:{
                    //当有人读取fullName时,get就会被调用,且返回值就作为fullName的值
                    //初次读取fullName会被调用get ,所依赖的数据发生变化的时候get也重新调用
                     get(){

                         return this.firstNam+"-"+this.lastName;
                     },
                     //set当fullName被修改时
                     set(value){
                        const arr=value.split("-");
                        this.firstNam=arr[0];
                        this.lastName=arr[1];
                     }
                } */
            },
            watch:{
                firstNam(newValue,oldValue){
                    this.fullName=newValue+'-'+this.lastName;
                },
                lastName(newValue, oldValue) {
                    this.fullName = this.firstNam + '-'+ newValue;
                },

            }
         

        })
    </script>
</body>
</html>

 

posted @ 2022-10-31 13:52  小白字太白  阅读(18)  评论(0编辑  收藏  举报