响应式变量
使用组合式API的方式定义响应式变量,必须通过ref 或reactive 函数来实现。
一、使用ref函数定义响应式变量
语法为:let xxx = ref(初始值) 。使用如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| <script setup name="App"> import { ref } from 'vue'
let username = ref('张三');
const onChangeUsername = () => { username.value = '李四'; } </script>
<template> <div>用户名:{{ username }}</div> <button @click="onChangeUsername">修改用户名</button> </template>
|
使用ref函数定义的响应式变量,有两点需要注意:
● 在模板中可直接使用变量。
● 在script标签中,若要操作变量,则需要通过username.value来实现。
二、使用reactive函数定义响应式变量
定义一些复合型响应式变量,则应该使用reactive 函数来实现。基本语法为:let xxx = reactive(源对象) 。使用如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
| <script setup name="App"> import { reactive } from 'vue'
let author = reactive({username: "张三", age: 18})
let books = reactive([ {name: '水浒传',author: '施耐庵'}, {name: '三国演义',author: '罗贯中'} ])
const onModifyBookName = () => { books[0].name = '红楼梦' }
const onUpdateUsername = () => { author.username = "李四" }
</script>
<template> <h1>用户名为:{{author.username}}</h1> <button @click="onUpdateUsername">修改用户名</button> <table> <thead> <tr> <th>书名</th> <th>作者</th> </tr> </thead> <tbody> <tr v-for="book in books" :key="book.name"> <td>{{ book.name }}</td> <td>{{ book.author }}</td> </tr> </tbody> </table> <button @click="onModifyBookName">修改书名</button> </template>
|
reactive 函数适合使用那些深层次的响应式变量。如果需要重新给reactive 函数定义的响应式变量赋值,那么需要通过Object.assign 来实现,否则将会失去响应式的功能:
1
| Object.assign(books, [{name: '红楼梦',author: '曹雪芹'}])
|
三、ref和reactive对比
● 如果要定义一个基本数据类型的响应式变量,则必须使用ref。
● 如果要定义一个层级不深的复合类型的响应式变量,则ref和reactive都可以。
● 如果要定义一个层级很深的复合类型的响应式变量,则推荐使用reactive。