|
@@ -0,0 +1,78 @@
|
|
|
+<script lang="ts" setup name="TheWelcome">
|
|
|
+import { reactive, watch } from "vue";
|
|
|
+
|
|
|
+// 定义一个响应式的对象
|
|
|
+const sum = reactive({
|
|
|
+ name: '请问',
|
|
|
+ age: 12,
|
|
|
+ car: {
|
|
|
+ c1: '宝马',
|
|
|
+ c2: '奔驰'
|
|
|
+ }
|
|
|
+});
|
|
|
+
|
|
|
+// 修改整个对象
|
|
|
+function changeC1() {
|
|
|
+ sum.car.c1 = "马萨拉蒂"
|
|
|
+}
|
|
|
+
|
|
|
+function changeC2() {
|
|
|
+ sum.car.c2 = "小米"
|
|
|
+}
|
|
|
+
|
|
|
+function changePerson() {
|
|
|
+ sum.car = {c1: "小米", c2: "马萨拉蒂"};
|
|
|
+}
|
|
|
+
|
|
|
+// 修改名称
|
|
|
+function changeName() {
|
|
|
+ sum.name = '而非';
|
|
|
+}
|
|
|
+
|
|
|
+// 增加年龄
|
|
|
+function changeAge() {
|
|
|
+ sum.age += 2;
|
|
|
+}
|
|
|
+
|
|
|
+// 情况四:监视响应式对象中的某个属性,且该属性时基本类型的,要写成函数式
|
|
|
+watch(() => sum.name, (newValue, oldValue) => {
|
|
|
+ console.log('变化了', newValue, oldValue);
|
|
|
+}, {deep: true, immediate: true});
|
|
|
+//结论:监视的要是对象里的属性,那么最好写函数式,注意点:若是对象监视的是地址值,需要关注对象内部,需要手动开启深度监视
|
|
|
+watch(() => sum.car, (newValue, oldValue) => {
|
|
|
+ console.log('变化了', newValue, oldValue);
|
|
|
+}, {deep: true, immediate: true}); //深度监视
|
|
|
+</script>
|
|
|
+
|
|
|
+<template>
|
|
|
+ <div class="TheWelcome">
|
|
|
+ <h1>情况一:监视【reactive】定义的【对象类型】数据</h1>
|
|
|
+ <h2>姓名:{{ sum.name }}</h2>
|
|
|
+ <h2>年龄:{{ sum.age }}</h2>
|
|
|
+ <h2>汽车:{{ sum.car.c1 }}、{{ sum.car.c2 }}</h2>
|
|
|
+ <!-- 按钮触发不同的修改操作 -->
|
|
|
+ <button @click="changeName">修改名称</button>
|
|
|
+ <button @click="changeAge">修改年龄</button>
|
|
|
+ <button @click="changeC1">直接修改第一台车</button>
|
|
|
+ <button @click="changeC2">直接修改第二台车</button>
|
|
|
+ <button @click="changePerson">直接修改全部车</button>
|
|
|
+ </div>
|
|
|
+</template>
|
|
|
+
|
|
|
+<style scoped>
|
|
|
+/*
|
|
|
+ .TheWelcome 类选择器,仅应用于当前组件内部的元素,
|
|
|
+ 因为使用了`scoped`属性,确保样式不会影响到其他组件
|
|
|
+*/
|
|
|
+.TheWelcome {
|
|
|
+ background-color: skyblue; /* 设置背景颜色 */
|
|
|
+ box-shadow: 0 0 10px; /* 添加阴影效果 */
|
|
|
+ border-radius: 10px; /* 设置圆角半径 */
|
|
|
+ padding: 20px; /* 设置内边距 */
|
|
|
+}
|
|
|
+
|
|
|
+/* 设置按钮之间的间距 */
|
|
|
+button {
|
|
|
+ margin: 0 5px;
|
|
|
+}
|
|
|
+</style>
|