只需在script标签中添加setup,组件只需引入不用注册,属性和方法也不用返回,也不用写setup函数,也不用写export default ,甚至是自定义指令也可以在我们的template中自动获得。
//原始写法
<template>
<div class="hello">
</div>
</template>
<script>
export default {
name: 'HelloWorld',
props: {
msg: String
},
setup(props,context){
}
}
</script>
//语法糖
<template>
<div class="hello">
</div>
</template>
<script setup>
</script>
接收父组件参数
//原始写法
<template>
<div class="hello">
{{msg}}
</div>
</template>
<script>
export default {
name: 'HelloWorld',
props:['msg'],
setup(props){
console.log(props.msg);
}
}
</script>
//语法糖
<template>
<div class="hello">
{{type.msg}}
</div>
</template>
<script setup>
import { defineProps } from 'vue'
const type = defineProps({msg:String})
console.log(type.msg);
</script>
子组件传递值给父组件
//原始写法 父组件
<template>
<HelloWorld msg="你好" @show="show"/>
</template>
<script>
import HelloWorld from './components/HelloWorld.vue'
export default {
name: 'App',
components: {
HelloWorld
},
setup(){
function show(value){
console.log(value);
}
return {
show
}
}
}
</script>
<style>
</style>
//原始写法 子组件
<template>
<div class="hello">
{{msg}}
<button @click="test">按钮</button>
</div>
</template>
<script>
export default {
name: 'HelloWorld',
props:['msg'],
setup(props,context){
function test(){
context.emit('show',123)
}
return{
test
}
}
}
</script>
//语法糖 父组件
<template>
<HelloWorld msg='你好' @show="show" />
</template>
<script setup>
import HelloWorld from './components/HelloWorld.vue'
function show(value){
console.log(value);
}
</script>
//语法糖 子组件
<template>
<div class="hello">
{{type.msg}}
</div>
<button @click="test">按钮</button>
</template>
<script setup>
import { defineProps,defineEmits } from 'vue'
const type = defineProps({msg:String})
const emit = defineEmits(['show'])
function test(){
emit('show',1212)
}
</script>
useSlots 和 useAttrs
attrs: 值为对象,包含:组件外部传递过来,但没有在props配置中声明的属性, 相当于 this.$attrs
。
slots: 收到的插槽内容, 相当于 this.$slots
。
//原始写法
<template>
</template>
<script>
export default {
name: 'HelloWorld',
setup(props,context){
console.log(context.slots)
console.log(context.attrs)
}
}
</script>
//语法糖
<script setup>
import { useSlots,useAttrs } from 'vue'
const slots = useSlots()
const attrs = useAttrs()
</script>
defineExpose
如果在父组件中通过ref的方法来获取子组件实例,
子组件使用了script setup语法糖,
则子组件的数据需要用defineExpose 的方式导出,否则不会暴露属性。
//语法糖父组件
<template>
<daughter ref="father" />
</template>
<script lang="ts" setup>
import { ref } from "vue";
import Daughter from "./vue/Daughter.vue";
const father = ref(null)
</script>
//语法糖子组件
<template>
<div>{{ msg }}</div>
</template>
<script lang="ts" setup>
import { ref ,defineExpose} from "vue";
const msg = ref('儿子')
defineExpose({
msg
})
</script>