ref:定义一个响应式的数据
使用方法:const xxx = ref(value)
修改时通过xxx.value = *** 修改
例如
<template>
<h1>一个人的信息</h1>
<h2>姓名:{{name}}</h2>
<h2>年龄:{{age}}</h2>
<h3>工作类型:{{job.type}}</h3>
<h3>工资:{{job.salary}}</h3>
<button @click="changeInfo">修改人的信息</button>
</template>
import { ref} from 'vue'
export default {
name: 'App',
setup(){
//ref函数返回RefImpl对象 值在此对象的value属性中
let name = ref('张三')
let age = ref(18)
letjob = ref({
type: '程序猿',
salary: '3k'
})
function changeInfo(){
name.value = '李四'
age.value = 25
job.value.type= '老师'
job.value.salary = '5k'
console.log(name,age)
}
// 返回一个对象(常用)
return {
name,
age,
changeInfo
}
}
}
reactive:定义一个对象类型的响应式数据
使用方法:const 代理对象 = reactive(源对象)
reactive定义的响应式数据是深层次的,内部基于ES6的Proxy实现
修改时不用通过.value 直接 对象名.属性名 即可
例如
<template>
<h1>一个人的信息</h1>
<h2>姓名:{{person.name}}</h2>
<h2>年龄:{{person.age}}</h2>
<h3>工作类型:{{person.job.type}}</h3>
<h3>工资:{{person.job.salary}}</h3>
<h1>{{hello[0]}}</h1>
<button @click="changeInfo">修改</button>
</template>
import { ref, reactive} from 'vue'
export default {
name: 'App',
setup(){
let person = reactive({
name: '张三',
age: 18,
job: {
type: '程序猿',
salary: '3k'
}
})
let hello= reactive(['hello', 'word'])
function changeInfo(){
person.name = '李四'
person.age = 48
person.job.type = '老师'
person.job.salary = '5k'
hello[0] = '你好'
}
// 返回一个对象(常用)
return {
person,
changeInfo
}
}
}