是Vue3中一个新的配置项,也是Vue3跟2最大的区别。又叫组合式API
组件中所用到的数据方法等,都要配置在setup中
setup() 的返回值,有两个
返回一个对象时,则对象中的属性,方法,都可以在模板中直接进行使用
<template>
<div class="App">
<p>姓名是:{
{ uname }}</p>
<p>年龄是:{
{ age }}</p>
<button @click="sayHi">sayHi</button>
</div>
</template>
<script>
export default {
name: 'App',
setup() {
// 直接声明的变量,是没有响应式的
let uname = '张三'
let age = 24
function sayHi() {
alert(`hello`)
}
// 变量和函数,必须返回出去以后才能使用
return {
uname,
age,
sayHi,
}
},
}
</script>
- 可以返回一个渲染函数,则可以直接自定义渲染的内容(了解)
<template>
<div class="App"></div>
</template>
<script>
import { h } from 'vue'
export default {
name: 'App',
setup() {
// setup()的返回值,可以是对象,也可以是一个渲染函数
// h('要渲染的标签','标签里的内容') h() 就是一个渲染函数
return () => h('h1', '渲染出来的')
},
}
</script>
setup() 有两个参数
props
一般用作接收组件外传递给组件内的数据
父组件
<template>
<div class="App">
<Son :msg="msg"></Son>
</div>
</template>
<script>
import Son from '@/components/Son.vue'
import { ref } from 'vue'
export default {
name: 'App',
components: {
Son,
},
setup() {
let msg = ref('传递给子组件的数据')
return {
msg,
}
},
}
</script>
子组件
<template>
<div class="son">123</div>
</template>
<script>
export default {
name: 'Son',
props: ['msg'],
setup(props) {
// props中就包含着组件外传过来的数据
console.log(props)
},
}
</script>
2. context
上下文对象,包含了一些组件的琐碎的东西
其中最重要的有三个,分别是
attrs
,emit
,slots
attrs
的值为对象,包含组件外部传递过来的,但是没有在props配置中声明的属性。也就是说没有被props接收的,都会被它接收,但是它没有办法对接收的数据做验证哦。相当于this.$attrs
slots
指收到的插槽的内容,相当于this.$slots
emit
也就是分发事件的函数,一般用作子传父,相当于this.$emit
emit
举例:
子组件
<template>
<div class="son">
子组件---<button @click="sendParent">点击发送给父组件数据</button>
</div>
</template>
<script>
import { ref } from 'vue'
export default {
name: 'Son',
props: ['msg'],
setup(props, context) {
console.log(context)
let num = ref(100)
function sendParent() {
context.emit('handle', num)
}
return {
sendParent,
}
},
}
</script>
父组件
<template>
<div class="App">
<Son :msg="msg" @handle="handle"></Son>
</div>
</template>
<script>
import Son from '@/components/Son.vue'
import { ref } from 'vue'
export default {
name: 'App',
components: {
Son,
},
// 以前报错,现在不声明自定义事件也不报错了
emits: ['handle'],
setup() {
let msg = ref('传递给子组件的数据')
function handle(val) {
console.log(val)
}
return {
msg,
handle,
}
},
}
</script>
注意点:
Vue3中也可以用Vue2的形式,但是不推荐,尽量不要混用
Vue2配置中是可以访问到setup()中的方法和属性,但是setup()中不能访问Vue2的配置
如果有重名冲突,以setup()的为准
setup()不能是一个async函数,因为返回值不再是return的对象,而是一个promise,模板就用不了对象中的属性
setup()
要先于beforeCreate
执行,所以setup()
中是不能用this
的
<template>
<div class="App"></div>
</template>
<script>
export default {
name: 'App',
beforeCreate() {
console.log('beforeCreate()执行')
},
setup() {
// 会输出这个,所以setup()内用不了了this
console.log('setup()函数开始执行了')
console.log(this) // undefined
return {}
},
}
</script>
setup()
中相当于集成了beforeCreate
和created
两个生命周期
原文链接:https://blog.csdn.net/qq_52845451/article/details/126671115
此处评论已关闭