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

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

父组件:parent.tsx

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

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

页面效果:
Vue3 setup tsx 子组件向父组件传值 emit_第1张图片

你可能感兴趣的:(#,Vue,3,javascript,vue.js,前端)