vue.js

关注公众号 jb51net

关闭
首页 > 网络编程 > JavaScript > javascript类库 > vue.js > Vue3 defineProps、defineEmits和defineExpose使用

Vue3之defineProps、defineEmits和defineExpose的使用及说明

作者:样子2018

文章介绍了Vue中defineProps、defineEmits和defineExpose的用途和作用,defineProps用于在子组件中定义类型安全的props,defineEmits允许子组件向父组件传递事件

一、使用说明

二、简单示例

<template>
    <div>
        <p>{{msg}} - {{exposeStr}} - {{count}}</p>
        <button @click="_click">set msg</button>
        <button @click="count++">加</button>
        <button @click="count--">减</button>
    </div>
</template>

<script setup>
    import {
        ref
    } from 'vue'
    
    const exposeStr = ref('')
    const count = ref(0)
    const open = () => {
        console.log('this is a open function')
    }
    
    const emit = defineEmits(['setMsg'])
    
    const props = defineProps({
        msg: {
            type: String,
            default: 'this is a test component'
        }
    })
    
    const _click = () => {
        emit('setMsg', {msg: props.msg})
    }
    
    defineExpose({
        exposeStr,
        open
    })
</script>

<style>
    
</style>
<script setup>
    import Test from './components/Test.vue'

    import {
        ref
    } from 'vue'
    
    const detail = ref('')
    const setMsg = (val) => {
        detail.value.exposeStr = "set expose msg"
        detail.value.open()
        console.log(val)
    }
</script>

<template>
    <Test ref="detail" msg="this is a test component" @setMsg="setMsg"></Test>
</template>

<style>

</style>

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

您可能感兴趣的文章:
阅读全文