joken-前端工程师

  博客园 :: 首页 :: 新随笔 :: :: :: 管理 ::

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 2024-09-08 21:47  joken1310  阅读(277)  评论(0)    收藏  举报