在script标签加setup属性
<script lang="ts" setup>
</script>
1.不用写setup函数,组件只需要引入不需要注册,属性和方法也不需要再返回,可以直接在template模板中使用。
2. setup语法糖中新增api
2.1 defineProps:子组件接收父组件中传来的props
2.2 defineEmits:子组件调用父组件中的方法
2.3 defineExpose:子组件暴露属性,可以在父组件中拿到
例:
父组件
<template>
<div class="wrap">
parent: {{ num }}
<el-button type="primary" @click="addNum">num + 1</el-button>
<childCom ref="childComRef" @on-change="changeNum" :num="num" />
</div>
</template>
<script lang="ts" setup>
import childCom from './coms/childCom.vue'
import { ref } from 'vue'
import { ElButton } from 'element-plus'
const num = ref(1)
const childComRef = ref()
const changeNum = (val) => {
num.value = val
}
const addNum = () => {
num.value++
console.log(childComRef.value.childData)
}
</script>
子组件
<template>
<div class="wrap">
child: {{ num }} <el-button type="primary" @click="setNum">set 6</el-button></div
>
</template>
<script lang="ts" setup>
import { defineProps, defineEmits, defineExpose } from 'vue'
import { ElButton } from 'element-plus'
defineProps({
// 接受父组件属性
num: {
type: Number,
default: 0
}
})
const emit = defineEmits(['on-change'])
const setNum = () => {
emit('on-change', 6) // 触发父组件的方法
}
const childData = 666
//暴露子组件属性
defineExpose({
childData
})
</script>