zoukankan      html  css  js  c++  java
  • vue---watch、computed和methods之间的区别

    let vm = new Vue({

      el: "#app"

      data: {

        firstname: '',

        lastname: '',

        fullname: '',

      },

      methods: {   //可用keyup动作绑定事件

        getFullname () {

          this.fullname = this.firstname + '-' + this.lastname

        }

      },

      watch: {

        firstname: function () {

          this.fullname = this.firstname + '-' + this.lastname

        },   //设置多个监听属性时用逗号分隔

        $route.path: function ( newval, oldval ) {   //监听路由的变化

          if (newval === '/login')  console.log('欢迎来到登录页面!')

          else if (newval === '/login')  console.log('欢迎来到注册页面!')

        }

      },

      computed: {

        fullname: function () {

          return this.firstname + '-' + this.lastname

      }

    }

    })

    总结:

    1. methods中写的是一些方法,用于处理业务逻辑;

    2. computed的本质是一个方法,但我们把他们的名称当做属性来使用,它的值通过在函数中的return来返回。当computed值所依赖的值发生变化时,这个computed值也会立即重新求值,且computed值的结果会被缓存起来,当它所依赖的数据都没有发生变化时,不会对它重新求值

    3. watch用于监听data中的以及其他(比如路由)的数据的变化,当被监听的内容发生变化时,触发相应的函数,从而进行某些逻辑操作。可以认为是methods和computed的结合体。

  • 相关阅读:
    怎样理解HTMLCollection接口
    怎样单独遍历NodeList的键、值和键值对
    怎样获取NodeList某位置上的节点
    怎样遍历NodeList对象
    怎样理解NodeList的动态集合与静态集合
    怎样将类似数组的对象转换为数组
    怎样理解 instanceof
    怎样清理当前节点下的所有文本节点
    怎样移除当前节点
    怎样判断一个节点是否相等 / 是否相同
  • 原文地址:https://www.cnblogs.com/Ryan368/p/11320745.html
Copyright © 2011-2022 走看看