父组件.vue

<template>
  <div class="home">
    <img alt="Vue logo" src="../assets/logo.png" />
      <!-- 父子组件传值和vue2.0的几乎没差多少 -->
    <HelloWorld :msg="data.msg" @todata="todata" />
  </div></template><script>// @ is an alias to /src
import HelloWorld from "@/components/HelloWorld.vue";
import { reactive } from "@vue/reactivity";
import { provide } from "@vue/runtime-core";

export default {
  name: "Home",
  components: {
    HelloWorld,
  },
  setup(props, context) {
    // 使用todata来接收子组件传来的值 最后return一下 切记一定要return 否则template找不到
    const todata = (data) => {
      console.log(data);
    };
    const data = reactive({
      msg: "Welcome to Your Vue.js App",
    });
    return { data, todata };
  },
};</script>

子组件.vue

<template>
  <div class="hello">
    <h1>{{ msg }}</h1>
  </div>
</template>

<script>
import { watch } from "vue";
export default {
  name: "HelloWorld",
  //如果不需要处理父组件的值直接写着一段即可,
  props: {
    msg: String,
  },
  setup(props, ctx) {
    //因为想监听一下这个父组件的值 所以需要在setup里面写一个props参数用来获取父组件传来的值
    const msg = props.msg;
    // 监听一下子组件的值
    watch(msg, (oldVal, newVal) => {
      console.log(oldVal);
      console.log(newVal);
    });
    //传值给父组件使用的方法 和vue2.0的$emit使用方法一样,vue3的emit没有$,别搞混了
    ctx.emit("todata", { msg: "ylg" });
  },
};
</script>