相对于以前的语法,使用语法糖之后语法变得相当简单和简短
<script setup>
</script>
注:vue3.2以上的版本才可使用,或者说比较合适
demo
无需setup函数,并且会自动return定义的变量等
<template>
{{msg}}
</template>
<script setup>
let msg = 'aaa'
</script>
注册组件
<template>
<login></login>
</template>
<script setup>
import login from 'login.vue'
</script>
传值
父 → 子
// 父
<template>
<subject-card :title="msg"></subject-card>
</template>
<script setup>
import subjectCard from '../components/subjectCard.vue'
const msg = 'aaa'
</script>
// 子
// subjectCard.vue
<template>
<div class="test">
{{title}}
</div>
</template>
<script setup>
const props = defineProps({
title:{
type: String
}
})
子 → 父
// 子
// subjectCard.vue
<script setup>
const emit = defineEmits(['clickThis'])
const clickThis = () => {
emit('clickThis', '这是子组件向父组件传的值')
}
</script>
// 父
<template>
<subject-card @clickThis="clickThis"></subject-card>
</template>
<script setup>
import subjectCard from '../components/subjectCard.vue'
const clickThis = e => {
console.log(e + '1')
}
</script>
对外暴露属性(defineExpose)
// 子
// subjectCard.vue
<script setup>
const color = 'pink'
defineExpose({
color
})
</script>
// 父
<template>
<subject-card ref="color"></subject-card>
</template>
<script setup>
import { ref } from "vue"
import subjectCard from '../components/subjectCard.vue'
let color = ref(null)
onMounted(() => {
console.log(color.value.color)
})
</script>
CSS使用变量
<script setup>
const color = 'pink'
</script>
<style lang="less" scoped>
background-color: v-bind(color);
</style>