Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use vue3's setup ()

2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article focuses on "how to use vue3's setup ()". Interested friends may wish to have a look at it. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn how to use vue3's setup ().

Upgrading from vue2 to vue3,vue3 is compatible with vue2, so vue3 can use vue2's optional API. As the optional API a variable exists in many places, if there is a problem, you need to go to multiple functions to check, when the project is large, encounter problems, increase the difficulty of troubleshooting. So a new setup configuration item has been added to vue3 to write combined API.

1. The difference between optional API and combined API some students have been using vue for a year, but they don't know the optional api! Are you that classmate? If it is, put it away.

Options API in vue2 is an optional api, one in Chinese and one in English, whatever you want.

In a vue file, data, methods, mounted, computed, watch, and so on are used to define properties and methods to deal with page logic together, which we call Options API.

Example 1: counter

+ {{num}}-export default {data () {return {num:0}}, methods: {add () {this.num++}, reduce () {this.num--} observe the above examples, we find that the processing of num values involves two options, data and methods, the business processing is relatively scattered, and the project is small and clear, but when the project becomes larger, data and methods will contain many properties and methods. At this point, it is difficult to tell which property corresponds to which method. So vue3 adds setup write combination API.

The Composition API of Vue3 is the combined api.

Combined api means that the api defined by a function will be put together, so that even if the project becomes larger and the function increases, we can quickly find all the api related to the function, unlike Options API, where the functions are scattered and need to be changed, it is difficult to find more than one place.

Example 2: counter

+ {{num}}-import {ref} from 'vue' export default {setup () {const num = ref (1) return {num, add () {num.value++}, reduce () {num.value--} ref makes the basic data type responsive. The next article details its usage. Students who need it can click to pay attention not to get lost!

Use a picture to tell you the difference:

Second, how to use setup exactly? 2.1.When will setup be implemented? Setup is used to write combinatorial api, which is equivalent to replacing beforeCreate from the point of view of life cycle hook function. Will be executed before creted.

After export default {created () {console.log ('created');}, setup () {console.log (' setup');}} is executed, the setup print result is always in front of it.

2.2.How are setup data and methods used? Example 3: define usage variables directly

An exception was found after running {{a}} export default {setup () {const a = 0}}:

Runtime-core.esm-bundler.js?5c40:6584 [Vue warn]: Property "a" was accessed during render but is not defined on instance.

Prompts us that the property a we accessed is not mounted on the instance.

The properties and methods within setup must be exposed by return and mounted to the instance, otherwise there is no way to use them. Add return in the above code:

Export default {setup () {const a = 0 return {a} 2.3.Is there a this inside setup? Print the this in setup, and the return result is undefined. It means that there is no this inside setup, and things related to this cannot be mounted.

2.4.How to use the hook function in setup?

Vue3 is an option that is compatible with vue2, so hook functions can exist side by side with setup, which is the equivalent of Options API.

Example 4:

Export default {setup () {console.log ('setup');}, mounted () {console.log (' mounted');}} vue3's new setup () function is used to write combined api, so it is not recommended to write code like this. So you need to use the functions of the onXXX family to register the hook function. After successful registration, a callback function is passed when it is called.

Example 5:

Import {onMounted} from "vue"; export default {setup () {const a = 0 return {a}, onMounted (() = > {console.log ("execution");})} registered lifecycle hook functions can only be used synchronously during setup because they rely on the global internal state to locate the current component instance and will not throw an error when the current component calls the function.

Other hook functions are the same, just introduce them as needed.

2.5.When setup and hook functions are juxtaposed with setup and hook functions, setup cannot call lifecycle-related functions, but lifecycle can call setup-related properties and methods.

Example 6:

Click export default {setup () {const a = 0 return {a}}, methods: {log () {console.log (this.$options.setup ()); / / return an object} this.$options.setup () returns a large object that contains all the properties and methods in the setup.

When the setup parameter uses setup, it will receive two parameters: props and context.

The first parameter of props is props, which means that the parent component passes a value to the child component. Props is responsive, and it is automatically updated when a new props is passed.

Example 7:

Export default {props: {msg: String, ans: String,}, setup (props,context) {console.log (props); / / Proxy {msg: "hurry to find someone", ans: "do you have a date?" },} because props is responsive and cannot be deconstructed using ES6, it will eliminate the response characteristics of prop, so you need to borrow toRefs to deconstruct. Example 8:

Import {toRefs} from "vue"; export default {props: {msg: String, ans: String,}, setup (props,context) {console.log (props); const {msg,ans} = toRefs (props) console.log (msg.value); / / hurry to find a date console.log (ans.value); / / do you have a date? },} when using components, we often encounter optional parameters, some places need to pass a certain value, and sometimes not, how to deal with it?

If ans is an optional parameter, there may be no ans in the incoming props. In this case, toRefs will not create a ref for ans, but will need to use toRef instead.

Import {toRef} from "vue"; setup (props,context) {let ans = toRef (props, 'ans') / / create an ans console.log (ans.value) when it does not exist;} 3.2, contextcontext context, which contains three parts: attribute, slot, and custom event.

Setup (props,context) {const {attrs,slots,emit} = context / / attrs gets the property value passed by the component. / / the slot / / emit custom event subcomponent in the slots component} attrs is a non-responsive object that mainly receives no-props attributes and is often used to pass style attributes.

Slots is a proxy object, where slots.default () gets an array, the length of the array is determined by the slot of the component, and the contents of the slot are in the array.

There is no this in the setup, so the emit is used to replace the previous this.$emit and to trigger a custom event when the child is passed on to the parent.

Example 9:

The child passes the value import {toRefs,toRef} from "vue" to the parent; export default {setup (props,context) {const {attrs,slots,emit} = context / / attrs get component passes the style attribute console.log ('slots',slots.default ()); / / slot array console.log (' slot property', slots.default () [1] .props) / / get the attribute return {attrs, emit}} of the slot. At this point, I believe you have a better understanding of "how to use vue3's setup ()". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report