欢迎光临
我们一直在努力

Vue3的setup函数如何使用

本篇内容介绍了“Vue3的setup函数如何使用”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!

Composition Api
setup函数是一个新的组件选项。作为在组件内使用Composition API的入口点。
调用时机:
setup函数会在beforeCreate钩子之前被调用
返回值
如果setup返回一个对象,则对象的属性可以在组件模板中被访问
参数
接收俩个参数

setup.vue

<template>
	<div>
		setup
	</div>
</template>
 
<script>
	export default{
		setup(){
			console.log('setup.....')
		},
		beforeCreate() {
			console.log('beforeCreate...')
		},
	}
</script>
 
<style>
</style>

app.vue

 <template>
	<comp-setup>

	</comp-setup>
</template>
 
<script>
/*eslint no-mixed-spaces-and-tabs: ["error", "smart-tabs"]*/
import CompSetup from './components/setupview'
export default {
  name: 'App',
  components: {
	  CompSetup,
  }
}
</script>
 
<style>
 
</style>

接收参数:

setup.vue

<template>
	<div>
		{{ name }}
		<p>{{ user.username }}</p>
	</div>
</template>
 
<script>
	export default{
		//setup不能访问this
		//可以接收参数
		setup(props,context){
			// console.log('setup.....')
			//这种返回的数据不具有响应式
			// let name='tom'
			// return {
			// 	name,
			// }
			return {
				name:'tom',
				user:{
					username:'admin',
					password:'123'
				}
			}
		},
		beforeCreate() {
			// console.log('beforeCreate...')
		},
		props:{
			msg:String
		}
	}
</script>
 
<style>
</style>

app.vue

<template>
	<comp-setup msg="welcome">

	</comp-setup>
</template>

<script>
/*eslint no-mixed-spaces-and-tabs: ["error", "smart-tabs"]*/
import CompSetup from './components/setupview'
export default {
  name: 'App',
  components: {
	  CompSetup,
  }
}
</script>

<style>

</style>

“Vue3的setup函数如何使用”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识可以关注云搜网网站,小编将为大家输出更多高质量的实用文章!

赞(0)
【声明】:本博客不参与任何交易,也非中介,仅记录个人感兴趣的主机测评结果和优惠活动,内容均不作直接、间接、法定、约定的保证。访问本博客请务必遵守有关互联网的相关法律、规定与规则。一旦您访问本博客,即表示您已经知晓并接受了此声明通告。