网站首页 > 知识剖析 正文
setup 函数是一个新的组件选项,它会在 beforeCreate 钩子之前被调用。
<template>
<div>
<img alt="Vue logo" src="./assets/logo.png">
<h1>vue3.0 beta</h1>
<div>{{ count }} {{ object.foo }}</div>
</div>
</template>
<script>
import { ref, reactive } from 'vue'
export default {
setup() {
console.log('setup')
const count = ref(0)
const object = reactive({ foo: 'bar' })
// 暴露给模板
return {
count,
object,
}
},
created(){
console.log('created')
},
beforeCreate(){
console.log('beforeCreate')
},
mounted(){
console.log('mounted')
},
beforeMount(){
console.log('beforeMount')
},
data(){
return {
age: 18
}
}
}
</script>
可以看到 setup 返回的对象是可以直接插入模板中使用的。其实 setup 里面能做的事情远远不止于这些,里面可以:
1、访问dada选项的数据
setup项链里面不存在 this 变量,this不能执行当前的引用的 vue 实例,这是vue3.0在设计之初刻意为之的。
因为setup 里面没有 this 变量,所以默认没办法访问 data 选项的数据,如需在 setup 里面访问,需要引入 getCurrentInstance 函数,如下引入方式:
setup项链里面不存在 this 变量,this不能执行当前的引用的 vue 实例,这是vue3.0在设计之初刻意为之的。 import { getCurrentInstance } from 'vue'
setup() {
const { ctx } = getCurrentInstance()
}
可以看到我们从 getCurrentInstance函数,取了ctx 属性,ctx 就相当于当前vue实例的引用。
2、执行生命周期
与 2.x 版本生命周期相对应的组合式 API
- beforeCreate -> 使用 setup()
- created -> 使用 setup()
- beforeMount -> onBeforeMount
- mounted -> onMounted
- beforeUpdate -> onBeforeUpdate
- updated -> onUpdated
- beforeDestroy -> onBeforeUnmount
- destroyed -> onUnmounted
- errorCaptured -> onErrorCaptured
3.0的setup里面的生命周期和2.x版本的有点区别,需要单独引入
import { onBeforeMount, onMounted, onBeforeUpdate, onUpdated, onBeforeUnmount, onUnmounted } from 'vue'
可以看到如果需要在 setup 选项使用生命周期函数。使用如下:
import { onBeforeMount, onMounted, onBeforeUpdate, onUpdated, onBeforeUnmount, onUnmounted } from 'vue'
setup() {
onBeforeMount(() => {
});
onMounted(() => {
});
}
猜你喜欢
- 2025-04-30 分享我的AI应用开发经验(ai应用开发工程师)
- 2025-04-30 小编带你分分钟了解并学会SEO(如何学好seo)
- 2025-04-30 bleach,一个超强的 Python 库!(python库教程)
- 2025-04-30 网贷平台通过提高网页信噪比优化关键词排名首页
- 2025-04-30 怎么把谷歌SEO做到100分(谷歌seo sem)
- 2025-04-30 一份优秀完整的网站SEO诊断报告应该这样写
- 最近发表
- 标签列表
-
- xml (46)
- css animation (57)
- array_slice (60)
- htmlspecialchars (54)
- position: absolute (54)
- datediff函数 (47)
- array_pop (49)
- jsmap (52)
- toggleclass (43)
- console.time (63)
- .sql (41)
- ahref (40)
- js json.parse (59)
- html复选框 (60)
- css 透明 (44)
- css 颜色 (47)
- php replace (41)
- css nth-child (48)
- min-height (40)
- xml schema (44)
- css 最后一个元素 (46)
- location.origin (44)
- table border (49)
- html tr (40)
- video controls (49)