zoukankan      html  css  js  c++  java
  • Vue.js学习笔记 第六篇 内置属性

    computed属性

    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="utf-8">
        <title></title>
        <script src="https://unpkg.com/vue"></script>
    </head>
    <body>
        <div id="app-1">
            <p>初始字符串:{{ content }}</p>
            <p>计算后字符串:{{ reversedContent }}</p>
        </div>
        <script type="text/javascript">
            var vm1 = new Vue({
                el: '#app-1',
                data: {
                    content: 'TanSea'
                },
                computed: {
                    reversedContent: function() {
                        return this.content.split('').reverse().join('')
                    }
                }
            })
        </script>
    </body>
    </html>

    Vue对象实例化时,之前接触过了el、data、methods,这里再介绍一个computed

    computed的定义和methods的定义是一样的,但是在理解上可以理解为methods是类的方法,computed是类的属性

    但是,computed默认是没有set方法的,我们可以显式的给他定义一个

    <div id="app-2">
        <p>初始字符串:{{ content }}</p>
        <p>计算后字符串:{{ reversedContent }}</p>
    </div>
    <script type="text/javascript">
        var vm2 = new Vue({
            el: '#app-2',
            data: {
                content: 'TanSea'
            },
            computed: {
                reversedContent: {
                    get: function() {
                        return this.content.split('').reverse().join('')
                    },
                    set: function(newValue) {
                        this.content = newValue
                    }
                }
            }
        })
    </script>

    这时,我们就可以在浏览器的控制台输入vm2.reversedContent = 'Hello, World'给他重新赋值了

    在大部分情况下,computed和methods是可以互换的,那么他们的区别是什么?

    computed 属性会基于它所依赖的数据进行缓存,只有在依赖的数据发生变化时,才会重新取值

    methods总是再次执行函数

    <div id="app-3">
        <p>初始字符串:{{ nowDate }}</p>
        <p>methods:{{ mNowDate() }}</p>
        <!-- Date.now()是非响应式的依赖数据,computed属性永远不会更新 -->
        <p>computed:{{ cNowDate }}</p>
    </div>
    <script type="text/javascript">
        var vm3 = new Vue({
            el: '#app-3',
            data: {
                nowDate: Date.now()
            },
            methods: {
                mNowDate: function() {
                    return Date.now()
                }
            },
            computed: {
                cNowDate: function() {
                    return Date.now()
                }
            }
        })
    </script>

    例子使用了Date.now()这种非响应式数据,computed在首次计算完成之后就不再更新

  • 相关阅读:
    升级linux bash
    vim关键字自动补全
    linux bash shell之变量替换::=句法、=句法、:句法、句法、=?句法、?句法、:+句法、+句法
    使用Bash编写Linux Shell脚本7.复合命令
    使用Bash编写Linux Shell脚本5.变量
    使用Bash编写Linux Shell脚本8.调试和版本控制
    Perl之单引号\双引号的字符串直接量
    linux bash shell 中的单引号和双引号
    使用Bash编写Linux Shell脚本6.表达式
    Vim的行号、语法显示等设置,即.vimrc文件的配置
  • 原文地址:https://www.cnblogs.com/TanSea/p/Vue-Chapter6-Attributes.html
Copyright © 2011-2022 走看看