vue的setup用法
时间: 2023-08-11 19:41:28 浏览: 52
`setup()` 是 Vue3 中的一个新特性,它是在组件创建期间执行的一个函数,用来替代 Vue2.x 中的 `beforeCreate()` 和 `created()` 钩子函数。
`setup()` 的主要作用是为组件提供响应式数据、计算属性、方法和生命周期钩子等。
它接收两个参数:`props` 和 `context`,其中 `props` 是组件的属性对象,`context` 是组件上下文对象,包含了 `attrs`、`slots`、`emit` 等属性。
下面是一个简单的示例:
```javascript
import { reactive } from 'vue'
export default {
props: {
msg: String
},
setup(props, context) {
const state = reactive({
count: 0
})
const increment = () => {
state.count++
}
return {
state,
increment
}
}
}
```
在上面的例子中,我们使用 `reactive` 函数创建了一个响应式数据对象 `state`,并通过 `return` 把它暴露出去。同时,我们还定义了一个方法 `increment`,用来修改 `state.count` 的值。
在模板中,我们可以这样使用暴露出来的数据和方法:
```html
<template>
<div>
<p>{{ msg }}</p>
<p>Count: {{ state.count }}</p>
<button @click="increment">Increment</button>
</div>
</template>
<script>
import { reactive } from 'vue'
export default {
props: {
msg: String
},
setup(props, context) {
const state = reactive({
count: 0
})
const increment = () => {
state.count++
}
return {
state,
increment
}
}
}
</script>
```