setup
简单介绍
起初Vue3.0版本变量和方法都是要 return
出来才可以使用,很不友好。在Vue3.2版本推出了 `setup` 语法糖之后,属性和方法都不需要 return 出去了,组件也不需要注册就可以直接使用了,下面慢慢来介绍。
setup基本语法
<template>
<div></div>
</template>
// 在script 标签加 setup
<script setup>
...
</script>
// 如果是用ts来写 则在script 标签加lang='ts'即可
<script lang="ts" setup>
...
</script>
属性和方式不用return
<template>
<div>
<div>{{ name }}</div>
<button @click="handleClick">click me</button>
</div>
</template>
<script setup>
import { ref } from 'vue'
// 属性跟方法都不需要return 在template就可以直接使用了
const name = ref('胡歌')
const handleClick = () => {
console.log('彭于晏');
}
</script>
<style>
</style>
组件不需要组册
<template>
<div>
<Child />
</div>
</template>
<script setup>
// 只需要引入组件就可以直接使用 不用注册
import Child from './child.vue'
import { ref } from 'vue'
</script>
defineProps
的使用
defineProps是子组件用来接收父组件传递的参数
// 父组件
<template>
<div>
<Child :name="name" :obj="obj" />
</div>
</template>
<script setup>
import Child from './child.vue'
import { ref, reactive } from 'vue'
const name = ref('胡歌')
const obj = reactive({
name: '胡歌',
age: 18
})
</script>
// 子组件
<template>
<div></div>
</template>
<script setup>
// Vue3.2版本setup语法糖 defineProps 不需要引入可以直接使用
const props = defineProps({
name: {
type: String,
default: ''
},
obj: {
type: Object,
default: () => {}
}
})
console.log('name', props.name); // 胡歌
console.log('obj', props.obj); // { name: '胡歌', age: 18 }
</script>
defineEmits
的使用
defineEmits主要是子组件给父组件传递参数的
// 父组件
<template>
<div>
<Child @myClick="myClick" />
</div>
</template>
<script setup>
import { ref, reactive } from 'vue'
import Child from './child.vue'
const myClick = val => {
console.log('val', val); // emit传递信息
}
</script>
// 子组件
<template>
<div>
<button @click="handleClick">click me</button>
</div>
</template>
<script setup>
// Vue3.2版本setup语法糖 defineEmits 不需要引入可以直接使用
const emit = defineEmits(['myClick']) // 如果有多个emit事件可以往数组后边添加即可
const handleClick = ()=>{
emit("myClick", "emit传递信息")
}
</script>
defineExpose
的使用
使用<script setup>
的组件是默认关闭的,也即通过模板 ref 或者$parent
链获取到的组件的公开实例,不会暴露任何在<script setup>
中声明的绑定。
为了在<script setup>
组件中明确要暴露出去的属性,使用defineExpose
// 父组件
<template>
<div>
<Child ref="myRef" />
<button @click="handleClick">click me</button>
</div>
</template>
<script setup>
import Child from './child.vue'
import { ref } from 'vue'
const myRef = ref(null)
const handleClick = () => {
console.log('myRef', myRef.value.name) // 胡歌
myRef.value.fn() // 梅长苏
}
</script>
// 子组件
<template>
<div>
<div></div>
</div>
</template>
<script setup>
// Vue3.2版本setup语法糖 defineExpose 不需要引入可以直接使用
defineExpose({
// 把 name 属性 和fn方法暴露出去
name: '胡歌',
fn () {
console.log('梅长苏')
}
})
</script>
如何给组件命名
<script setup>
import { ref } from 'vue'
...
</script>
// 再加一个script给组件命名即可
<script>
export default {
name: 'Name',
}
</script>
async和await的使用
不必再配合 async 就可以直接使用 await 了。代码会被编译成async setup()
<script setup>
const post = await fetch(`/api/post/1`).then(r => r.json())
</script>