vue3 setup
时间: 2023-11-17 08:46:12 浏览: 123
Vue 3 introduces a new function called `setup` to replace the options-based API used in Vue 2. The `setup` function allows you to initialize component state, define computed properties, and set up component lifecycle hooks.
In Vue 3, the `setup` function is executed before the component is created, providing a more explicit and flexible way to define component logic. Here's an example of how to use the `setup` function:
```javascript
<template>
<div>
<p>{{ message }}</p>
<button @click="increment">Increment</button>
</div>
</template>
<script>
import { ref } from 'vue';
export default {
setup() {
const message = ref('Hello Vue 3');
function increment() {
message.value += '!';
}
return {
message,
increment
};
}
};
</script>
```
In the example above, we import `ref` from the `vue` package, which allows us to create a reactive reference. Inside the `setup` function, we declare a `message` variable using `ref`, and a function called `increment` that appends an exclamation mark to the message. We then return these variables and functions as an object from the `setup` function.
By using the `setup` function, you can access reactive properties and functions directly in the template without the need for the `this` context. This makes the code more concise and easier to read.
I hope this helps! Let me know if you have any further questions.
阅读全文