这两个属性很重要、ref用于声明基本类型的数据,例如字符串、数字。reactive通常用来声明复杂类型数据,例如数组和对象等。只有通过以上两个关键词修饰的变量,才会动态响应。
在组合式 API 中,推荐使用 ref()
函数来声明响应式状态:
ref()
接收参数,并将其包裹在一个带有 .value
属性的 ref 对象中返回:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>ref使用</title>
</head>
<div id="app">
姓名:{{name}}
<br>
年龄:{{age}}
</div>
<body>
<script type="module">
import { createApp, ref } from './vue.esm-browser.js'
//声明vue对象
createApp({
setup() {
//声明响应式变量name和age
const name = ref("姓名")
const age = ref(18)
console.log(age) // RefImpl {dep: Dep, __v_isRef: true, __v_isShallow: false, _rawValue: 18, _value: 18}
console.log(age.value) // 18
return {
name,
age
}
},
}).mount("#app")
</script>
</body>
</html>
import 引入 ref
记得return声明的变量
注意,在模板中使用 ref 时,我们不需要附加 .value
。为了方便起见,当在模板中使用时,ref 会自动解包。
ref 声明的变量,打印出来是响应式数据接口。而age.value则是值
还有另一种声明响应式状态的方式,即使用 reactive()
API。与将内部值包装在特殊对象中的 ref 不同,reactive()
将使对象本身具有响应性:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>reactive使用</title>
</head>
<div id="app">
姓名:{{user.name}}
<br>
年龄:{{user.age}}
<br>
喜欢的颜色:{{user.color}}
<br>
爱好:{{user.hobby}}
</div>
<body>
<script type="module">
import { createApp, reactive } from './vue.esm-browser.js'
//声明vue对象
createApp({
setup() {
//声明响应式变量user
const user = reactive({
name: '张三',
age: 18,
color: ['red', 'blue'],
hobby: {
name: '收件人',
address: '内蒙古'
}
})
return {
user
}
},
}).mount("#app")
</script>
</body>
</html>
import 引入reactive
return user
值得注意的是,reactive()
返回的是一个原始对象的 Proxy,它和原始对象是不相等的:
const raw = {}
const proxy = reactive(raw)
// 代理对象和原始对象不是全等的
console.log(proxy === raw) // false
缺点!WARNING]