package.json
{
"name": "vue3_test",
"version": "0.1.0",
"private": true,
"scripts": {
"serve": "vue-cli-service serve",
"build": "vue-cli-service build"
},
"dependencies": {
"core-js": "^3.8.3",
"vue": "^3.2.13",
"vue-router": "^4.0.3",
"vuex": "^4.0.0"
},
"devDependencies": {
"@vue/cli-plugin-babel": "~5.0.0",
"@vue/cli-plugin-router": "~5.0.0",
"@vue/cli-plugin-vuex": "~5.0.0",
"@vue/cli-service": "~5.0.0"
}
}
TestView.vue
<template>
<div class="home">
<Child name="test" :people="people"></Child>
</div>
</template>
<script setup>
import { ref, defineProps } from "vue";
import Child from "@/components/Child.vue";
const people = ref('');
setTimeout(() => {
people.value = {
id: 'id1',
age: '100',
flag: true
}
}, 3000);
setTimeout(() => {
people.value = {
id: 'id111',
age: '10000',
flag: false
}
}, 5000);
</script>
Child.vue
<template>
<div class="child">
<div>{{ name }}</div>
<div>{{ people.id }}</div>
<div>{{ people.age }}</div>
<div>{{ people.flag }}</div>
</div>
</template>
<script setup>
import { ref, watch } from "vue";
const props = defineProps({
name: {
type: String,
default: "123",
},
people: {
type: Object,
default: {},
},
});
/*
watch 默认是懒执行的:仅当数据源变化时,才会执行回调。
但在某些场景中,我们希望在创建侦听器时,立即执行一遍回调。
举例来说,我们想请求一些初始数据,然后在相关状态更改时重新请求数据。
我们可以通过传入 immediate: true 选项来强制侦听器的回调立即执行
*/
watch(
() => props.people.id,
(newVal) => {
console.log(newVal)
},
{
immediate: true
}
);
</script>
测试结果