Vue基础-Computed-Watch

一、computed计算属性使用

1.复杂data的处理方式

我们知道,在模板中可以直接通过插值语法显示一些data中的数据。

但是在某些情况,我们可能需要对数据进行一些转化后再显示,或者需要将多个数据结合起来进行显示;

  • 比如我们需要对多个data数据进行运算、三元运算符来决定结果、数据进行某种转化后显示;
  • 在模板中使用表达式,可以非常方便的实现,但是设计它们的初衷是用于简单的运算;
  • 在模板中放入太多的逻辑会让模板过重和难以维护
  • 并且如果多个地方都使用到,那么会有大量重复的代码;

我们有没有什么方法可以将逻辑抽离出去呢?

  • 可以,其中一种方式就是将逻辑抽取到一个method中,放到methods的options中;
  • 但是,这种做法有一个直观的弊端,就是所有的data使用过程都会变成了一个方法的调用;
  • 另外一种方式就是使用计算属性computed

2.认识计算属性computed

什么是计算属性呢?

  • 官方并没有给出直接的概念解释;
  • 而是说:对于任何包含响应式数据的复杂逻辑,你都应该使用计算属性;
  • 计算属性将被混入到组件实例中
    • 所有 getter 和 setter 的 this 上下文自动地绑定为组件实例;

计算属性的用法:

  • 选项:computed
  • 类型:{ [key: string]: Function | { get: Function, set: Function } }

那接下来我们通过案例来理解一下这个计算属性。

3.案例实现思路

我们来看三个案例:

案例一:我们有两个变量:firstNamelastName,希望它们拼接之后在界面上显示;

案例二:我们有一个分数:score

  • 当score大于60的时候,在界面上显示及格;
  • 当score小于60的时候,在界面上显示不及格;

案例三:我们有一个变量message,记录一段文字:比如Hello World

  • 某些情况下我们是直接显示这段文字;
  • 某些情况下我们需要对这段文字进行反转;

我们可以有三种实现思路:

  • 思路一:在模板语法中直接使用表达式;
  • 思路二:使用method对逻辑进行抽取;
  • 思路三:使用计算属性computed;

4.实现思路一:模板语法

思路一的实现:模板语法

  • 缺点一:模板中存在大量的复杂逻辑,不便于维护(模板中表达式的初衷是用于简单的计算);
  • 缺点二:当有多次一样的逻辑时,存在重复的代码;
  • 缺点三:多次使用的时候,很多运算也需要多次执行,没有缓存;
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>

  <div id="app">
    <!-- 插值语法表达式直接进行拼接 -->
    <!-- 1.拼接名字 -->
    <h2>{{ firstName + " " + lastName }}</h2>
    <h2>{{ firstName + " " + lastName }}</h2>
    <h2>{{ firstName + " " + lastName }}</h2>

    <!-- 2.显示分数等级 -->
    <h2>{{ score >= 60 ? '及格': '不及格' }}</h2>

    <!-- 3.反转单词显示文本 -->
    <h2>{{ message.split(" ").reverse().join(" ") }}</h2>
  </div>
  
  <script src="../lib/vue.js"></script>
  <script>
    // 1.创建app
    const app = Vue.createApp({
      // data: option api
      data() {
        return {
          // 1.姓名
          firstName: "kobe",
          lastName: "bryant",

          // 2.分数: 及格/不及格
          score: 80,

          // 3.一串文本: 对文本中的单词进行反转显示
          message: "my name is why"
        }
      },
    })

    // 2.挂载app
    app.mount("#app")
  </script>
</body>
</html>

5.实现思路二:method实现

思路二的实现:method实现

  • 缺点一:我们事实上先显示的是一个结果,但是都变成了一种方法的调用;
  • 缺点二:多次使用方法的时候,没有缓存,也需要多次计算;
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>

  <div id="app">
    <!-- 插值语法表达式直接进行拼接 -->
    <!-- 1.拼接名字 -->
    <h2>{{ getFullname() }}</h2>
    <h2>{{ getFullname() }}</h2>
    <h2>{{ getFullname() }}</h2>

    <!-- 2.显示分数等级 -->
    <h2>{{ getScoreLevel() }}</h2>

    <!-- 3.反转单词显示文本 -->
    <h2>{{ reverseMessage() }}</h2>
  </div>
  
  <script src="../lib/vue.js"></script>
  <script>
    // 1.创建app
    const app = Vue.createApp({
      // data: option api
      data() {
        return {
          // 1.姓名
          firstName: "kobe",
          lastName: "bryant",

          // 2.分数: 及格/不及格
          score: 80,

          // 3.一串文本: 对文本中的单词进行反转显示
          message: "my name is why"
        }
      },
      methods: {
        getFullname() {
          return this.firstName + " " + this.lastName
        },
        getScoreLevel() {
          return this.score >= 60 ? "及格": "不及格"
        },
        reverseMessage() {
          return this.message.split(" ").reverse().join(" ")
        }
      }
    })

    // 2.挂载app
    app.mount("#app")
  </script>
</body>
</html>

6.思路三的实现:computed实现

思路三的实现:computed实现

  • 注意:计算属性看起来像是一个函数,但是我们在使用的时候不需要加(),这个后面讲setter和getter时会讲到;
  • 我们会发现无论是直观上,还是效果上计算属性都是更好的选择;
  • 并且计算属性是有缓存的;
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>

  <div id="app">
    <!-- 插值语法表达式直接进行拼接 -->
    <!-- 1.拼接名字 -->
    <h2>{{ fullname }}</h2>
    <h2>{{ fullname }}</h2>
    <h2>{{ fullname }}</h2>

    <!-- 2.显示分数等级 -->
    <h2>{{ scoreLevel }}</h2>

    <!-- 3.反转单词显示文本 -->
    <h2>{{ reverseMessage }}</h2>
  </div>
  
  <script src="../lib/vue.js"></script>
  <script>
    // 1.创建app
    const app = Vue.createApp({
      // data: option api
      data() {
        return {
          // 1.姓名
          firstName: "kobe",
          lastName: "bryant",

          // 2.分数: 及格/不及格
          score: 80,

          // 3.一串文本: 对文本中的单词进行反转显示
          message: "my name is why"
        }
      },
      computed: {
        // 1.计算属性默认对应的是一个函数
        fullname() {
          return this.firstName + " " + this.lastName
        },

        scoreLevel() {
          return this.score >= 60 ? "及格": "不及格"
        },

        reverseMessage() {
          return this.message.split(" ").reverse().join(" ")
        }
      }
    })

    // 2.挂载app
    app.mount("#app")
  </script>
</body>
</html>

二、computed和method区别

1.计算属性 vs methods

在上面的实现思路中,我们会发现计算属性和methods的实现看起来是差别是不大的,而且我们多次提到计算属性有缓存的。

接下来我们来看一下同一个计算多次使用,计算属性和methods的差异:

在这里插入图片描述

2.计算属性的缓存

这是什么原因呢?

  • 这是因为计算属性会基于它们的依赖关系进行缓存;
  • 数据不发生变化时,计算属性是不需要重新计算的;
  • 但是如果依赖的数据发生变化,在使用时,计算属性依然会重新进行计算;

在这里插入图片描述

三、computed的set和get

1.计算属性的setter和getter

计算属性在大多数情况下,只需要一个getter方法即可,所以我们会将计算属性直接写成一个函数。

但是,如果我们确实想设置计算属性的值呢?

  • 这个时候我们也可以给计算属性设置一个setter的方法;
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>

  <div id="app">
    <h2>{{ fullname }}</h2>

    <button @click="setFullname">设置fullname</button>
  </div>
  
  <script src="../lib/vue.js"></script>
  <script>
    // 1.创建app
    const app = Vue.createApp({
      // data: option api
      data() {
        return {
          firstname: "coder",
          lastname: "why"
        }
      },
      computed: {
        // 语法糖的写法
        // fullname() {
        //   return this.firstname + " " + this.lastname
        // },
        
        // 完整的写法:
        fullname: {
          get: function() {
            return this.firstname + " " + this.lastname
          },
          set: function(value) {
            const names = value.split(" ")
            this.firstname = names[0]
            this.lastname = names[1]
          }
        }
      },
      methods: {
        setFullname() {
          this.fullname = "kobe bryant"
        }
      }
    })

    // 2.挂载app
    app.mount("#app")
  </script>
</body>
</html>

2.源码如何对setter和getter处理呢?(了解)

你可能觉得很奇怪,Vue内部是如何对我们传入的是一个getter,还是说是一个包含setter和getter的对象进行处理的呢?

  • 事实上非常的简单,Vue源码内部只是做了一个逻辑判断而已;

在这里插入图片描述

四、侦听器watch选项使用

1.认识侦听器watch

什么是侦听器呢?

  • 开发中我们在data返回的对象中定义了数据,这个数据通过插值语法等方式绑定到template中;
  • 当数据变化时,template会自动进行更新来显示最新的数据;
  • 但是在某些情况下,我们希望在代码逻辑中监听某个数据的变化,这个时候就需要用侦听器watch来完成了;

侦听器的用法如下:

  • 选项:watch
  • 类型:{ [key: string]: string | Function | Object | Array}

2.侦听器案例

举个栗子(例子):

  • 比如现在我们希望用户在input中输入一个问题
  • 每当用户输入了最新的内容,我们就获取到最新的内容,并且使用该问题去服务器查询答案;
  • 那么,我们就需要实时的去获取最新的数据变化;
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>

  <div id="app">
    <h2>{{message}}</h2>
    <button @click="changeMessage">修改message</button>
  </div>
  
  <script src="../lib/vue.js"></script>
  <script>
    // Proxy -> Reflect
    // 1.创建app
    const app = Vue.createApp({
      // data: option api
      data() {
        return {
          message: "Hello Vue",
          info: { name: "why", age: 18 }
        }
      },
      methods: {
        changeMessage() {
          this.message = "你好啊, 李银河!"
          this.info = { name: "kobe" }
        }
      },
      watch: {
        // 1.默认有两个参数: newValue/oldValue
        message(newValue, oldValue) {
          console.log("message数据发生了变化:", newValue, oldValue)
        },
        info(newValue, oldValue) {
          // 2.如果是对象类型, 那么拿到的是代理对象
          // console.log("info数据发生了变化:", newValue, oldValue)
          // console.log(newValue.name, oldValue.name)

          // 3.获取原生对象
          // console.log({ ...newValue })
          console.log(Vue.toRaw(newValue))
        }
      }
    })

    // 2.挂载app
    app.mount("#app")
  </script>
</body>
</html>

3.侦听器watch的配置选项

我们先来看一个例子:

  • 当我们点击按钮的时候会修改info.name的值;
  • 这个时候我们使用watch来侦听info,可以侦听到吗?答案是不可以。

这是因为默认情况下,watch只是在侦听info的引用变化,对于内部属性的变化是不会做出响应的:

  • 这个时候我们可以使用一个选项deep进行更深层的侦听;
  • 注意前面我们说过watch里面侦听的属性对应的也可以是一个Object;

还有另外一个属性,是希望一开始的就会立即执行一次:

  • 这个时候我们使用immediate选项;
  • 这个时候无论后面数据是否有变化,侦听的函数都会有限执行一次;
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>

  <div id="app">
    <h2>{{ info.name }}</h2>
    <button @click="changeInfo">修改info</button>
  </div>
  
  <script src="../lib/vue.js"></script>
  <script>
    // 1.创建app
    const app = Vue.createApp({
      // data: option api
      data() {
        return {
          info: { name: "why", age: 18 }
        }
      },
      methods: {
        changeInfo() {
          // 1.创建一个新对象, 赋值给info
          // this.info = { name: "kobe" }

          // 2.直接修改原对象某一个属性
          this.info.name = "kobe"
        }
      },
      watch: {
        // 默认watch监听不会进行深度监听
        // info(newValue, oldValue) {
        //   console.log("侦听到info改变:", newValue, oldValue)
        // }

        // 进行深度监听
        info: {
          handler(newValue, oldValue) {
            console.log("侦听到info改变:", newValue, oldValue)
            console.log(newValue === oldValue)
          },
          // 监听器选项:
          // info进行深度监听
          deep: true,
          // 第一次渲染直接执行一次监听器
          immediate: true
        },
        "info.name": function(newValue, oldValue) {
          console.log("name发生改变:", newValue, oldValue)
        }
      }
    })

    // 2.挂载app
    app.mount("#app")
  </script>
</body>
</html>

五、侦听器watch其他写法

1.字符串方法名

{
    watch: {
        title: 'method1'
    }
}

2.回调数组

你可以传入回调数组,它们会被逐一执行

{
    watch: {
        title: [
            function handler1(newvalue, oldvalue) {},
            function handler2(newvalue, oldvalue) {},
            function handler3(newvalue, oldvalue) {},
        ]
    }
}

3.侦听对象属性

另外一个是Vue3文档中没有提到的,但是Vue2文档中有提到的是侦听对象的属性:

{
    watch: {
        'info.title': function(newValue, oldValue) {}
    }
}

4.$watch

还有另外一种方式就是使用 $watch 的API:

我们可以在created的生命周期(后续会讲到)中,使用 this.$watchs 来侦听;

  • 第一个参数是要侦听的源;
  • 第二个参数是侦听的回调函数callback;
  • 第三个参数是额外的其他选项,比如deep、immediate;
{
    created() {
        this.$watch("message", (newValue, oldValue) => {
          console.log("message数据变化:", newValue, oldValue)
        }, { deep: true })
    }
}

六、案例练习

1.列表选中

<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    .active {
      color: red;
    }
  </style>
</head>
<body>

  <div id="app">
    <ul>
      <!-- <h2 :class="{title: false}"></h2> -->

      <!-- 对active的class进行动态绑定 -->
      <!-- 需求一: 将索引值为1的li添加上active -->
      <!-- 需求二:用一个变量(属性)记录当前点击的位置 -->
      <li :class="{active: index === currentIndex}"
          @click="liClick(index)"
          v-for="(item, index) in movies">
        {{item}}
      </li>
    </ul>
  </div>
  
  <script src="../lib/vue.js"></script>
  <script>
    // 1.创建app
    const app = Vue.createApp({
      // data: option api
      data() {
        return {
          movies: ["星际穿越", "阿凡达", "大话西游", "黑客帝国"],
          currentIndex: -1
        }
      },
      methods: {
        liClick(index) {
          console.log("liClick:", index)
          this.currentIndex = index
        }
      }
    })

    // 2.挂载app
    app.mount("#app")
  </script>
</body>
</html>

2.购物车

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    table,td,th {
      border-collapse: collapse;
      border: 1px solid #000;
    }
    td,th {
      padding: 10px;
      text-align: center;
    }
  </style>
</head>
<body>
  <div id="app">
    <template v-if="bookList.length > 0">
      <table>
        <tr>
          <th>序号</th>
          <th>书籍名称</th>
          <th>出版日期</th>
          <th>价格</th>
          <th>购买数量</th>
          <th>操作</th>
        </tr>
        <tr v-for="(book, index) in bookList" :key="book">
          <td>{{ index + 1 }}</td>
          <td>{{ book.name }}</td>
          <td>{{ book.publishDate }}</td>
          <td>¥{{ book.price }}</td>
          <td>
            <button :disabled="book.count === 0" 
            @click="sub(book)">-</button>
            {{ book.count }}
            <button @click="add(book)">+</button>
          </td>
          <td>
            <button @click="remove(book)">移除</button>
          </td>
        </tr>
      </table>
      <h2>总价:{{ totalPrice }}</h2>
    </template>
    <h2 v-else="bookList.length === 0">购物车为空</h2>
    
  </div>
  
  <script src="./js/vue.js"></script>
  <script>
   const vue = Vue.createApp({
      data: function () {
        return {
          bookList: [
            {
              name: "算法导论",
              publishDate: "2006-9",
              price: 85,
              count: 0
            },
            {
              name: "UNIX编程艺术",
              publishDate: "2006-10",
              price: 78,
              count: 0
            },
            {
              name: "编程珠玑",
              publishDate: "2006-2",
              price: 59,
              count: 0
            },
            {
              name: "代码大全",
              publishDate: "2008-1",
              price: 128,
              count: 0
            }
          ],
          totalPrice: 0
        }
      },
      methods: {
        sub(book) {
          book.count--;
        },
        add(book) {
          book.count++;
        },
        remove(book) {
          this.bookList.splice(this.bookList.indexOf(book), 1);
        }
      },
      watch: {
        bookList: {
          handler() {
            if (this.bookList.length === 0) {
              return;
            }
            // 计算总价
            this.totalPrice = this.bookList
            .map(value => value.count*value.price)
            .reduce((preValue, curValue) => preValue + curValue)
          },
          deep: true,
          immediate: true
        }
      }
    });
    vue.mount("#app");
  </script>

</body>
</html>
  • 24
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值