标题vue3:语法糖内的defineProps及defineEmits

1、defineProps

获取组件传值

<div :style="fontstyle">
        <div class="rate" @mouseout="mouseOut">
            <span  @mouseover="mouseOver(num)" v-for="num in 5" :key="num"></span>
            <!-- <span class="hollow" :style="fontWidth">
                <span @mouseover="mouseOver(num)" v-for="num in 5" :key="num"></span>
            </span> -->
            <span class="hollow" :style="fontWidth">
                <span @click="onRate(num)" @mouseover="mouseOver(num)" v-for="num in 5" :key="num"></span>
            </span>
        </div>
    </div>
    <script setup lang="ts">
 import { defineProps, defineEmits, computed, ref } from "vue"

// defineProps<{ // 采用ts专有声明,无默认值
// value: Number,
// theme?: String
// }>()

// 采用ts专有声明,有默认值
interface Props {
    value: number
    theme: string
}
const props = withDefaults(defineProps<Props>(), {
    value: 0,
    theme: 'blue'
})

// 非ts专有声明
// let props = defineProps({ 
//     value: Number,
//     theme: {
//         type: String,
//         default: 'blue'
//     }
// })

let width = ref(props.value)

function mouseOver(i: number) {
    width.value = i
}

function mouseOut() {
    width.value = props.value
}
const fontWidth = computed(() => `width: ${width.value}em;`)
const themeObj: { [key: string]: string } = { 'black': '#000', 'white': '#f80', 'red': '#f5222d', 'orange': '#8f0', 'yellow': '#80f', 'green': '#0f6', 'blue': '#08f',}
const fontstyle = computed(() => `color: ${themeObj[props.theme]};`)
</script>

<style>
.rate {
    position: relative;
    display: inline-block;
}
.rate > span.hollow {
    position: absolute;
    display: inline-block;
    top: 0;
    left: 0;
    width: 0;
    overflow: hidden;
}
</style>

2、defineEmits

子组件向父组件事件传递

<template>
    <div :style="fontstyle">
        <div class="rate" @mouseout="mouseOut">
            <span  @mouseover="mouseOver(num)" v-for="num in 5" :key="num"></span>
            <!-- <span class="hollow" :style="fontWidth">
                <span @mouseover="mouseOver(num)" v-for="num in 5" :key="num"></span>
            </span> -->
            <span class="hollow" :style="fontWidth">
                <span @click="onRate(num)" @mouseover="mouseOver(num)" v-for="num in 5" :key="num"></span>
            </span>
        </div>
    </div>
</template>
<script setup lang="ts">
 import { defineProps, defineEmits, computed, ref } from "vue"
***同上代码省略
// 非ts声明
// let emits = defineEmits(['update-rate'])
// function onRate(num) {
//    emits('update-rate', num)
// }
// 采用ts专有声明,
let emits = defineEmits<{(e: 'update-rate', num: number): void}>()
function onRate(num: number) {
    emits('update-rate', num)
}
</script>

<style>
// 同上代码
</style>
Logo

前往低代码交流专区

更多推荐