首页 > 其他 > 详细

computed计算属性,方法与watch侦听器

时间:2020-01-04 20:57:49      阅读:87      评论:0      收藏:0      [点我收藏+]
<div id="app">
    <div>{{fullName}}</div>
</div>
<script>
    var vm = new Vue({
        el: "#app",
        data: {
            name: "<h1>Dell</h1>",
            firstName: "sheng",
            lastName: "jun yong",
            age: 28
        },
        // 方式一:
        // 调用一次,执行一次,data数据更新页面重新渲染,该方法又会被调用,性能不佳
        methods: {
            // fullName: function(){
            //     return this.firstName + this.lastName
            // }
        },
        // 方式二
        // 计算属性有缓存,第一次调用执行一次,只要与其相关属性不变,多次调用只会执行一次方法,节约性能
        computed: {
            // 调用{{fullName}}无需括号,fullName相当于一个属性this.fullName,该方法的返回值就是属性值
            fullName() {
                return this.firstName + this.lastName
            }
        },
        // 方式三
        watch: {
            // 监听firstName数据,当firstName变化,该方法被回调
            firstName(){
                console.log("监听firstName")
                this.fullName = this.firstName + this.lastName
            },
            // 监听lastName数据,当lastName变化,该方法被回调
            lastName(){
                console.log("监听lastName")
                this.fullName = this.firstName + this.lastName
            }
        }
    })
</script>

 

computed计算属性,方法与watch侦听器

原文:https://www.cnblogs.com/shengjunyong/p/12150222.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!