[Vue]computed和watch的区别

发布时间 2023-10-25 13:22:29作者: 夕苜19

computed 和 watch 之间的区别:
  1. computed 能完成的功能,watch 都可以完成。
  2. watch 能完成的功能,computed 不一定能完成,例如: watch 可以进行异步操作。
两个重要的小原则:
  1.所有被 Vue 管理的函数,最好写成普通函数,这样 this 的指向才是 vm 或组件实例对象。
  2.所有不被 Vue 所管理的函数(定时器的回调函数、ajax 的回调函数等),最好写成箭头函数。这样 this 的指向才是 vm 或组件实例对象。

 

<body>
    <div id="root">
        姓:<input type="text" v-model="first_name">
        <br>
        名:<input type="text" v-model="last_name">
        <br>
        <p>----&gt; {{ full_name }}</p>
        <p>----&gt; {{ full_name }}</p>
    </div>
</body>
<script>
    let vm = new Vue({
        el: "#root",
        data: {
            first_name: '',
            last_name: '',
            full_name: ''
        },
        watch: {
            first_name(new_value, old_value) {
                console.log('first_name changed!');
                setTimeout(() => {
                    this.full_name = new_value + '-' + this.last_name
                }, 1000);
            },

            last_name(new_value, old_value) {
                console.log('last_name changed!');
                this.full_name = this.first_name + '-' + new_value
            },
        },
        methods: {
        }
    })
</script>