joken-前端工程师

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: :: :: 管理 ::
  404 随笔 :: 39 文章 :: 8 评论 :: 20万 阅读

emits 定义结构和使用

  • 子组件
import { defineComponent, PropType, h, computed, ref, watch } from 'vue';

export default defineComponent({
    name: 'PageF',
    props: {
        render: {
            type: Function,
            required: true // required定义必须
        },
        params1: {
            type: String,
            default: 'default value', // 设置默认值
            required: true
        }
    },
    //定义emits结构
    emits: {
        change: (val: number) => true //固定返回true
    },
    setup(props, ctx) {
        const { render } = props;

        const param0 = computed(() => props.params1); // 监听 props.params1 的变化
        const param1 = ref(props.params1); // 内部独立的 ref

        console.log(param1, 'param1');

        // 监听 param1 的变化
        watch(param1, () => {
            console.log(param1.value, 'param1_change');
        });

        // 监听 param0 的变化
        watch(param0, () => {
            console.log(param0.value, 'param0_change');
        });

        return () => {
            return (
                <div>
                    <button onClick={() => ctx.emit('change', 121212)}>btn</button>
                </div>
            );
        };
    }
});

  • 父组件使用
<template>
    <div class="component-name">
        <child :render="render" :params1="abc" @change="handleChange" />
    </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, nextTick } from 'vue';
import child from './components/child';
import { ElInput } from 'element-plus';
const abc = ref('sdlfkjsdfj');
const render = (h) => {
    const text = ref('');
    return h('input', {
        type: 'text',
        modelValue: text.value, // 使用modelValue 而不是value传递输入框的值
        onInput: (e) => {
            text.value = e.target.value; // 更新 text.value
        }
    });
};

function handleChange(val) {
    console.log(val, 'number_sdlvnsdlfsjlfj');
}

setTimeout(() => {
    abc.value = '中文';
}, 3000);
</script>

<style lang="scss" scoped></style>

其他使用方式记录

image

image

image

posted on   joken1310  阅读(140)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异
· 三行代码完成国际化适配,妙~啊~
点击右上角即可分享
微信分享提示