1.属性和方法
属性和方法无需返回,直接使用
<template>
<div>
<Foo />
<h2 @click="increment">{{ count }}</h2>
</div>
</template>
<script setup>
import { ref } from 'vue'
import Foo from './components/Foo.vue'
const count = ref(0)
const increment = () => count.value++
</script>
会被编译为
// 导入的模块会被抽离到模块级别
import { ref } from 'vue'
import Foo from './components/Foo.vue'
export default {
setup() {
const count = ref(0)
const increment = () => count.value++
// 这是一个返回h函数的render函数
// 因为被编译到了setup函数中,所以可以直接访问顶层定义的属性和方法
return () => ([
h(Foo, null, ''),
h('h2', {
count,
onClick: increment
}, count)
])
}
}
2.组件自动注册
<template>
<div>
<Foo />
</div>
</template>
<!-- 在script标签上添加setup属性,以使用 script setup 语法 -->
<script setup>
import Foo from './components/Foo.vue'
</script>
3.props和emits
子组件
<template>
<div>
<h2>{{ count }}</h2>
<button @click="$emit('increment')">+1</button>
<button @click="decrement">-1</button>
</div>
</template>
<script setup>
// 接收props,并返回一个对象,可以在js中使用props来获取传入的数据
const props = defineProps({
count: {
type: Number,
default: 0
}
})
// 声明需要触发的事件,返回一个emit函数,作用和this.$emit函数的作用是一致的
const emit = defineEmits(['increment', 'decrement'])
const decrement = () => emit('decrement')
</script>
父组件
<template>
<div>
<Foo :count="count" @increment="increment" @decrement="decrement" />
</div>
</template>
<script setup>
import { ref } from 'vue'
import Foo from './components/Foo.vue'
const count = ref(0)
const increment = () => count.value++
const decrement = () => count.value--
</script>
-
defineProps 和 defineEmits 是编译器宏(compiler macros )
只能在
<script setup>
中使用。它们不需要被导入,并且在处理<script setup>
时被编译掉。 -
传递给 defineProps 和 defineEmits 的选项将被从 setup 中提升到模块范围。
因此,这些选项不能引用在 setup 作用域内声明的局部变量。这样做会导致一个编译错误。