使用reactive函数可以定义对象类型、数组类型的响应式数据。
看个具体的例子。
import { createApp } from 'vue';
import App from './App.vue';
createApp(App).mount('#app')
<template>
<h1>个人信息</h1>
<h2>姓名:{{name}}</h2>
<h2>年龄:{{age}}</h2>
<h2>岗位:{{job.position}}</h2>
<h2>薪酬:{{job.salary}}</h2>
<h2>爱好:{{hobby}}</h2>
<button @click="changeInfo">修改个人信息</button>
</template>
<script>
import {ref,reactive} from "vue";
export default {
name: 'App',
setup(){
let name = ref("张三");
let age = ref(18);
let job = reactive({
position:"前端工程师",
salary:"30k"
});
let hobby = reactive(['跑步','游泳','阅读']);
function changeInfo(){
name.value = "李四";
age.value = 28;
job.position = "Java工程师";
job.salary = "60k";
hobby[0] = '吃饭';
hobby[1] = '睡觉';
hobby[2] = '打豆豆';
}
return {
name,
age,
job,
hobby,
changeInfo
}
}
}
</script>
- 启动应用,测试效果
|