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>
    );
  },
});

页面效果:

相关推荐
猿饵块27 分钟前
cmake--get_filename_component
java·前端·c++
好多吃的啊37 分钟前
背景图鼠标放上去切换图片过渡效果
开发语言·javascript·ecmascript
大表哥638 分钟前
在react中 使用redux
前端·react.js·前端框架
Passion不晚40 分钟前
打造民国风格炫酷个人网页:用HTML和CSS3传递民国风韵
javascript·html·css3
十月ooOO42 分钟前
【解决】chrome 谷歌浏览器,鼠标点击任何区域都是 Input 输入框的状态,能看到输入的光标
前端·chrome·计算机外设
qq_3391911443 分钟前
spring boot admin集成,springboot2.x集成监控
java·前端·spring boot
pan_junbiao1 小时前
Vue使用代理方式解决跨域问题
前端·javascript·vue.js
明天…ling1 小时前
Web前端开发
前端·css·网络·前端框架·html·web
子非鱼9211 小时前
【JavaScript】LeetCode:41-45
开发语言·javascript·leetcode·链表·二叉树
ROCKY_8171 小时前
web前端-HTML常用标签-综合案例
前端·html