1、父组件
<template>
<Children :count="count" :info="info" />
</template>
<script setup lang="ts">
import { ref, reactive } from "vue";
import Children from "./Comp.vue";
const count = ref(0);
const info = ref({
age: 18,
});
setTimeout(() => {
count.value++;
//info.value.age = 98
info.value = { age: 99 };
}, 1000);
</script>
2、子组件,方式一
<template>
<div>{{ localcount }}</div>
<div>{{ info }}</div>
<button @click="onClick">点击</button>
</template>
<script setup lang="ts">
import { watchEffect, watch } from "vue";
const { count: localcount = 0, info = { age: 17 } } = defineProps<{
count: number;
info: object;
}>();
const onClick = () => {
console.log(localcount);
};
watchEffect(() => {
console.log("watchEffect:count:", localcount);
});
watch(() => localcount,
() => { console.log("watch:count:", localcount); })
</script>
3、子组件,方式二
/watch(count,
() => { console.log("watch:count:", count.value); })<template>
<div>{{ count }}</div>
<div>{{ info }}</div>
<button @click="onClick">点击</button>
</template>
<script setup lang="ts">
import { toRef, toRefs,watchEffect,watch } from "vue";
const props = defineProps<{
count: number;
info: object;
}>();
// 2种写法都行。
// const count = toRef(props, "count");
// const info = toRef(props, "info");
const { count, info } = toRefs(props);
const onClick = () => {
console.log(count.value);
};
watchEffect(() => {
console.log("watchEffect:count:", count.value);
});
watch(() => count.value,
() => { console.log("watch:count:", count.value); })
//或者
watch(count,
() => { console.log("watch:count:", count.value); })
</script>
标签:count,info,const,log,props,watch,value,解构,Vue3
From: https://www.cnblogs.com/springsnow/p/18432736