vue3中写钩子函数拿值
时间: 2023-11-19 13:07:26 浏览: 32
根据提供的引用,Vue 3中的生命周期钩子函数可以使用组合式API来实现。组合式API是Vue 3中的新特性,它允许我们使用函数来组织组件的逻辑,而不是像Vue 2中那样使用选项对象。在组合式API中,我们可以使用ref函数来创建响应式数据,使用computed函数来创建计算属性,使用watch函数来监听数据变化等等。
下面是一个示例代码,演示如何在Vue 3中使用组合式API来写钩子函数并拿到值:
```vue
<template>
<div>
<p>当前计数:{{ count }}</p>
<button @click="increment">增加</button>
</div>
</template>
<script>
import { ref, onMounted } from 'vue'
export default {
setup() {
const count = ref(0)
const increment = () => {
count.value++
}
onMounted(() => {
console.log('组件挂载完成')
console.log('当前计数:', count.value)
})
return {
count,
increment
}
}
}
</script>
```
在上面的代码中,我们使用了ref函数来创建一个响应式数据count,并在setup函数中返回了count和increment函数。在onMounted钩子函数中,我们可以拿到count的值并输出到控制台中。