使用组合式API的方式定义响应式变量,必须通过ref
或reactive
函数来实现。
语法为:let xxx = ref(初始值)
。使用如下:
<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
函数来实现。基本语法为:let xxx = reactive(源对象)
。使用如下:
<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
来实现,否则将会失去响应式的功能:
Object.assign(books, [{name: '红楼梦',author: '曹雪芹'}])
ref
。ref
和reactive
都可以。reactive
。