第三节:options API

118 阅读5分钟

附:「这是我参与2022首次更文挑战的第12天,活动详情查看:2022首次更文挑战

1. 复杂data的处理方式

(1)在模板(template)中我们可以直接通过插值语法(Mustache) 显示一些data中的数据。但是在某些情况,我们需要对data中的数据进行一些处理后再显示,或者需要将多个数据结合起来进行显示。例如:

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

(2)我们有没有什么办法可以将逻辑抽离出去呢?

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

2. 计算属性(Computed)

2.1 什么是计算属性?

官方并没有给出直接的概念解释,而是说:对于任何包含响应式数据的复杂逻辑,你都应该使用计算属性;

2.2 案例

(1)案例一:我们有两个变量:firstName和lastName,希望它们拼接之后在界面上显示;

(2)案例二:我们有一个分数:score,当score大于60的时候,在界面上显示及格;当score小于60的时候,在界面上显示不及格;

(3)案例三:我们有一个变量message,记录一段文字:比如Hello World。某些情况下我们是直接显示这段文字; 某些情况下我们需要对这段文字进行反转;

2.2.1 思路一:模板语法
<!DOCTYPE html>
<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"></div>

  <template id="my-app">
    <div>{{ firstName + lastName}}</div>
    <div>{{ score >= 60 ? '及格' : '不及格'}}</div>
    <div>{{ message.split(' ').reverse().join(' ') }}</div>
  </template>

  <script src="https://unpkg.com/vue@next"></script>
  <script>
    const App = {
      template: '#my-app',
      data() {
        return {
          firstName: '青年',
          lastName: '大学习',
          score: 70,
          message: 'Hello World'
        }
      }
    }

    Vue.createApp(App).mount('#app');
  </script>
</body>
</html>

输出结果:

2.2.2 思路二:methods
<!DOCTYPE html>
<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"></div>

    <template id="my-app">
        <div>{{ getFullName() }}</div>
        <div>{{ getResult() }}</div>
        <div>{{ getReverseMessage() }}</div>
    </template>

    <script src="https://unpkg.com/vue@next"></script>
    <script>
        const App = {
            template: '#my-app',
            data() {
                return {
                    firstName: '青年',
                    lastName: '大学习',
                    score: 70,
                    message: 'Hello World'
                }
            },
            methods: {
                getFullName(){
                    return this.firstName + this.lastName
                },
                getResult(){
                    return this.score >=60 ? "及格" : "不及格"
                },
                getReverseMessage(){
                    return this.message.split(' ').reverse().join(' ')
                }
            }
        }

        Vue.createApp(App).mount('#app');
    </script>
</body>

</html>

输出结果:

2.2.3 思路三:computed
<!DOCTYPE html>
<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"></div>

    <template id="my-app">
        <div>{{ fullName }}</div>
        <div>{{ result }}</div>
        <div>{{ reverseMessage }}</div>
    </template>

    <script src="https://unpkg.com/vue@next"></script>
    <script>
        const App = {
            template: '#my-app',
            data() {
                return {
                    firstName: '青年',
                    lastName: '大学习',
                    score: 70,
                    message: 'Hello World'
                }
            },
            computed:{
                fullName(){
                    return this.firstName + this.lastName
                },
                result(){
                    return this.score >= 60 ? "及格" : "不及格"
                },
                reverseMessage(){
                    return this.message.split(" ").reverse().join(" ")
                }
            }
        }

        Vue.createApp(App).mount('#app');
    </script>
</body>

</html>

输出结果:

2.2.3 三种思路区别

(1)思路一:模板语法

  • 缺点一:模板中存在大量的复杂逻辑,不便于维护(模板中表达式的初衷是用于简单的计算);
  • 缺点二:当有多次一样的逻辑时,存在重复的代码;
  • 缺点三:多次使用的时候,很多运算也需要多次执行,没有缓存;

(2)思路二:methods

  • 缺点一:我们事实上先显示的是一个结果,但是都变成了一种方法的调用;
  • 缺点二:多次使用方法的时候,没有缓存,也需要多次计算;

(3)思路三:computed

  • 计算属性看起来像是一个函数,但是我们在使用的时候不需要加()。我们会发现无论是直观上,还是效果上计算属性都是更好的选择; 并且计算属性是有缓存的;

2.3 计算属性 VS methods

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

<!DOCTYPE html>
<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"></div>

  <template id="my-app">
    <!-- 1. methods -->
    <h2>methods</h2>
    <div>{{ getFullName() }}</div>
    <div>{{ getFullName() }}</div>
    <div>{{ getFullName() }}</div>

    <hr>
    <!-- 2. computed -->
    <h2>computed</h2>
    <div>{{ fullName }}</div>
    <div>{{ fullName }}</div>
    <div>{{ fullName }}</div>

  </template>

  <script src="https://unpkg.com/vue@next"></script>
  <script>
    const App = {
      template: '#my-app',
      data() {
        return {
          fristName: "我爱",
          lastName: "跑步"
        }
      },
      computed:{
          fullName(){
              console.log("调用了计算属性中的fullName");
              return this.fristName + this.lastName;
          }
      },
      methods: {
          getFullName(){
              console.log("调用了getFullName方法");
              return this.fristName + this.lastName;
          }
      }
    }

    Vue.createApp(App).mount('#app');
  </script>
</body>
</html>

输出结果:可以看到methods调用了多次,而computed只调用了一次,这个就是计算属性的缓存功能。

2.4 计算属性的缓存

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

如图:计算属性是有缓存的,只有当数据变化后才会重新计算。

2.5 计算属性的setter和getter

计算属性在大多数情况下,只需要一个getter方法即可,所以我们会将计算属性直接写成一个函数。但是,如果我们确实想设置计算属性的值呢?这个时候我们也可以给计算属性设置一个setter的方法;

如图:

3. 侦听器(Watch)

3.1 什么是侦听器?

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

3.2 案例

比如现在我们希望用户在input中输入一个问题; 每当用户输入了最新的内容,我们就获取到最新的内容,并且使用该问题去服务器查询答案; 那么,我们就需要实时的去获取最新的数据变化;

<!DOCTYPE html>
<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"></div>

    <template id="my-app">
        <input type="text" v-model="question">
        <button @click="getResult">查找答案</button>
    </template>

    <script src="https://unpkg.com/vue@next"></script>
    <script>
        const App = {
            template: '#my-app',
            data() {
                return {
                    question: "如何成为全栈工程师?",
                }
            },
            methods: {
                getResult() {
                    console.log(`${this.question}问题的答案是哈哈哈哈`);
                }
            },
            watch: {
                question(newValue, oldValue) {
                    console.log(`新值:${newValue},旧值:${oldValue}`);
                }
            }
        }

        Vue.createApp(App).mount('#app');
    </script>
</body>

</html>

3.3 配置选项

3.3.1 深度监听(deep)

(1)我们先来看一个例子: 当我们点击按钮的时候会修改info.name的值; 这个时候我们使用watch来侦听info,可以侦听到吗?答案是不可以。示例代码如下:

<!DOCTYPE html>
<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"></div>

    <template id="my-app">
        <h2>info.name:{{info.name}}</h2>
        <button @click="modifyInfo">修改info</button>
        <button @click="modifyInfoName">修改info.name</button>
    </template>

    <script src="https://unpkg.com/vue@next"></script>
    <script>
        const App = {
            template: '#my-app',
            data() {
                return {
                    info: {
                        name: "小何",
                        age: 18
                    }
                }
            },
            methods: {
                modifyInfo() {
                    this.info = "小明";
                },
                modifyInfoName() {
                    this.info.name = "小明";
                }
            },
            watch: {
              // 默认的情况下我们的侦听器只会针对监听的数据本身的改变(内部发生的改变是不能侦听)
                info(newInfo, oldInfo) {
                    console.log(newInfo, oldInfo);
                }
            }
        }

        Vue.createApp(App).mount('#app');
    </script>
</body>

</html>

输出结果:

  • this.info 会触发watch,因为是监听数据本身的改变
  • this.info.name 不会触发watch,因为不是数据本身(内部发生的改变是不能侦听)

这是因为默认情况下,watch只是在侦听info的引用变化,对于内部属性的变化是不会做出响应的:这个时候我们可以使用一个选项deep进行更深层的侦听;

watch: {
     info: {
          handler(newValue, oldValue) {
              console.log(newValue, oldValue);
             },
             // 开启深度监听
             deep: true,
          }
     }

当我们开启深度监听(deep)后,此时再点击修改 info.name ,就能监听都info内部数据的变化了。

3.3.2 立即执行(immediate)

无论数据是否有变化,侦听的函数都会至少执行一次。

watch: {
     info: {
          handler(newValue, oldValue) {
              console.log(newValue, oldValue);
             },
             // 开启深度监听
             deep: true,
             // 开启立即执行
             immediate: true
          }
     }

3.4 侦听器其他使用方式

(1)Vue3文档中没有提到的,但是Vue2文档中有提到的是侦听对象的属性,示例代码如下:

// 当我们开启deep后,对象下所有的属性都会被监听到。如果你只想监听对象下的某一个属性,可以这样操作。
'info.name': function(newValue,oldValue){
  console.log(newValue,oldValue)
}

输出结果:

(2)另外一种就是使用 $watch 的 API,我们可以再created的生命周期中,使用 this.$watch来做侦听。

  • 第一个参数是要侦听的源
  • 第二个参数是侦听的回调函数
  • 第三个参数是额外的配置选项,例如:deep、immediate
created(){
 this.$watch('message',(newValue,oldValue) =>{
  console.log(newValue,oldValue)
 },{deep: true, immediate: true})
}

补充知识点:使用 $watch API,可以取消侦听器(具体使用方法可参考百度)。参考图片如下:

4. 综合案例

4.1 所用到的知识点

以下是我在写综合案例时,所用到的知识点,几乎把前几章所学到的知识点都用到了。

  1. 事件监听 -> @
  2. 列表渲染 -> v-for
  1. 计算属性 -> 计算商品的总价格
  2. v-if的使用 -> 当购物车没有书籍时,显示当前购物车为空
  1. 表格的使用
  2. 按钮处理逻辑(当数量为0时,按钮被禁用)

4.2 案例代码

index.html

<!DOCTYPE html>
<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>
    <link rel="stylesheet" href="./style.css">
</head>

<body>

    <div id="app"></div>

    <template id="my-app">
        <table v-if="books.length > 0">
            <thead>
                <th></th>
                <th>书籍名称</th>
                <th>出版日期</th>
                <th>价格</th>
                <th>购买数量</th>
                <th>操作</th>
            </thead>
            <tbody>
                <tr v-for="(book,index) in books">
                    <td>{{index + 1}}</td>
                    <td>{{book.name}}</td>
                    <td>{{book.date}}</td>
                    <td>{{"¥" + book.price}}</td>
                    <td>
                        <button :disabled="book.count <= 1" @click="decrement(index)">-</button>
                        <span class="counter">{{book.count}}</span>
                        <button @click="increment(index)">+</button>
                    </td>
                    <td>
                        <button @click="remove(index)">移除</button>
                    </td>
                </tr>
            </tbody>
        </table>
        <p v-else>当前购物车为空~</p>
        <h2>总价格:{{ "¥" + totalPrice }}</h2>
    </template>

    <script src="https://unpkg.com/vue@next"></script>
    <script src="./main.js"></script>
</body>

</html>

style.css

table {
    border: 1px solid #e9e9e9;
    border-collapse: collapse;
    border-spacing: 0;
  }
  
  th, td {
    padding: 8px 16px;
    border: 1px solid #e9e9e9;
    text-align: left;
  }
  
  th {
    background-color: #f7f7f7;
    color: #5c6b77;
    font-weight: 600;
  }
  
  .counter {
    margin: 0 5px;
  }
  

main.js

Vue.createApp({
    template: "#my-app",
    data() {
        return {
            books: [{
                    id: 1,
                    name: '《算法导论》',
                    date: '2006-9',
                    price: 85.00,
                    count: 1
                },
                {
                    id: 2,
                    name: '《UNIX编程艺术》',
                    date: '2006-2',
                    price: 59.00,
                    count: 1
                },
                {
                    id: 3,
                    name: '《编程珠玑》',
                    date: '2008-10',
                    price: 39.00,
                    count: 1
                },
                {
                    id: 4,
                    name: '《代码大全》',
                    date: '2006-3',
                    price: 128.00,
                    count: 1
                },
            ]
        }
    },
    methods: {
        increment(index) {
            this.books[index].count++
        },
        decrement(index) {
            this.books[index].count--
        },
        remove(index) {
            this.books.splice(index, 1)
        }
    },
    computed: {
        totalPrice() {
            let finalPrice = 0;
            this.books.map(item => {
                finalPrice += item.count * item.price
            })
            return finalPrice
        }
    }
}).mount("#app");

输出结果: