vue学习05--Vuejs中computed、methods、watch的区别[2]

看了很多资料,官方文档、博客、论坛等,写出以下例子,可看出部分区别:
当然,我个人简单理解如下:(并不准确,甚至错误,望大神纠正补充,感激不尽)
computed有缓存,若相关数据未发生变化,则不调用;
methods无缓存,需要事件才能调用它(如点击等);
watch多用于数据交互频繁的内容。(例如定时axios从服务器获取数据)


<html>
    <head>
        <meta charset="UTF-8">
        <title>title>
        <script src="../js/vue.js" type="text/javascript" charset="utf-8">script>
    head>
    <body>
        <p id="computed">哈利波特的英文是:{{fullName}}p>
        <p id="methods">赵四的昵称是:{{zhaosi()}}p>
        <p id="watch">被粉丝称呼为"胖迪"的是:{{name}}p>
        <script type="text/javascript">
            var vm = new Vue({
                el:"#computed",
                data:{
                    fn:"harry",
                    ln:"potter"
                },
                computed:{
                    fullName:function(){
                        return this.fn+" "+this.ln
                    }
                }
            })
            var vm1 = new Vue({
                el:"#methods",
                data:{
                    fn1:"尼古拉斯·",
                    ln1:"赵四"
                },
                methods:{
                    zhaosi:function(){
                        return this.fn1+" "+this.ln1
                    }
                }
            })
            var vm2 = new Vue({
                el:"#watch",
                data:{
                    fn2:"迪丽",
                    ln2:"热巴",
                    name:"迪丽热巴"
                },
                watch:{
                    fn2:function(val){
                        this.name = val+" "+this.ln2
                    },
                    ln2:function(val){
                        this.name = this.fn2+" "+val
                    }
                }
            })
        script>
    body>
html>

下图为methods和computed的区别:
vue学习05--Vuejs中computed、methods、watch的区别[2]_第1张图片

下图为computed和watch的区别:
vue学习05--Vuejs中computed、methods、watch的区别[2]_第2张图片

在此,注意:
1、计算属性computed是计算一些简单的数据的,不能有参数,但是必须有返回值
2、计算属性默认只有 getter ,不过在需要时你也可以提供一个 setter 。

你可能感兴趣的:(vue学习05--Vuejs中computed、methods、watch的区别[2])