Vue3 setup tsx 子组件向父组件传值 emit

需求:Vue3 setup 父组件向子组件传值,子组件接收父组件传入的值;子组件向父组件传值,父组件接收的子组件传递的值。

父组件:parent.tsx

javascript 复制代码
import { defineComponent, ref, reactive } from 'vue';
import TotalPreview from './components/TotalPreview'

export default defineComponent({
  name: 'parent',
  components: { TotalPreview },
  setup() {
    const count = ref(123);
    const childNum = reactive({ num: 1 });
    const onChildClick = (val: any) => {
      childNum.num = val;
      console.log('childNum',childNum); // 打印子组件向父组件传递的值
    };
    return () => (
      <>
        <div>
          <h1>父组件接收的子组件传递的值:{childNum.num}</h1>
          <TotalPreview num={count.value} onNumClick={onChildClick} />
        </div>
      </>
    );
  },
});

子组件:TotalPreview.tsx

javascript 复制代码
import { defineComponent, ref } from 'vue';
import { Button } from 'ant-design-vue';

export default defineComponent({
  name: 'Child',
  props: { num: Number },
  emits: ["numClick"],
  setup(props, { emit }) {
    const parentNum = ref(props.num)
    const count = ref(1);
    const onclick = () => {
      count.value++
      // emit 子组件向父组件传值
      emit('numClick', count.value);
    }

    return () => (
      <div>
        <h1>{'父组件传递给子组件的值:'+parentNum.value}</h1>
        <h1>{'子组件显示count值:'+count.value}</h1>
        <Button onClick={onclick}>点击按钮改变子组件的值,并向父组件传值</Button>
      </div>
    );
  },
});

页面效果:

相关推荐
IT_陈寒1 小时前
JavaScript项目实战经验分享
前端·人工智能·后端
用户47949283569152 小时前
6w star,GitHub 趋势第一的 Ponytail,这个agent插件到底在火什么
前端·后端
薛定喵的谔3 小时前
我开源了一个精致的 Next.js 博客模板:Skyplume
前端·前端框架·next.js
张龙6874 小时前
构建生产级 AI Agent:工具调用与记忆架构实战指南
前端
kyriewen5 小时前
2026 年了,还在用 Node.js?Bun 迁移实战:20 分钟搞定,附踩坑记录
前端·javascript·node.js
青山Coding6 小时前
Cesium应用(八):物体运动的实现思路
前端·cesium
用户41659673693556 小时前
Android WebView 加载 file:// 离线页面调试教程
android·前端
Asmewill6 小时前
curl命令学习笔记一
前端
我是一只快乐的小螃蟹6 小时前
1.2 ArrayList 源码解析
前端
星栈6 小时前
我用 Rust + Dioxus 做了个全栈跨平台笔记应用:再把新建、编辑和交付补上
前端·rust·前端框架