“This article has participated in the call for good writing activities, click to view: the back end, the big front end double track submission, 20,000 yuan prize pool waiting for you to challenge!”

The setup function features and functions

To be sure, Vue3.0 is compatible with the vue2. x version, which means we can use the syntax of vue2. x in our daily work, but when you start writing projects using Vue3 you will find it much more convenient than vue2. x

Vue 2.0 lifecycle compared to 3.0 lifecycle

Cycle name | | 2.0 3.0 cycle name | | | beforeCreate | setup before | | create component | created | setup | component has been created | | beforeMount | OnBeforeMount | component mounted before | | mounted | onMounted | component mounted complete | | beforeUpdate | onBeforeUpdate | data update, Virtual DOM patch before | | updated | onUpdated | data update, Virtual DOM render complete | | beforeDestroy | onBeforeUnmount | component destroyed before | | destroyed | onUnmounted | | after component destroyedCopy the code

One of Vue3’s features is —- setup

1.

BeforeCreate: indicates that the component is Created and data and methods of the component are not initialized. Setup Created: indicates that the component is Created and data and methods of the component are initializedCopy the code

The setup function is an entry point to the Composition API

All variables and methods defined in the setup function need to return or they cannot be used in the template

Setup function:

Created lifecycle methods are not executed at setup time, so data and methods variables and methods cannot be used in setup functions

2. Since we cannot use data and methods in setup functions, Vue directly changes this to undefined in order to avoid our incorrect use

Setup functions must be synchronous, not asynchronous

Usage 1: Used in conjunction with ref

<template> <div id="app"> {{name}} <p>{{age}}</p> <button @click="plusOne()">+</button> </div> </template> <script> Import {ref} from 'vue' export default {name:'app', data(){return {name:' Beijing '}}, Setup (){// name const name =ref(' little ') // age const age=ref(18) // function plusOne(){age.value++ // Return {name,age,plusOne}}} </script>Copy the code

Usage 2: Code splitting

Options API and Composition API

Options API conventions:

We need to set the receive parameter in props. There is no this in setup

We need to set variables inside data

We need to set computing properties in computed

We need to set the listening properties in watch

We need to set event methods inside methods

You’ll notice that the Options APi dictates where we should do what, which in turn forces us to split code to some extent. Now with the Composition API, this is no longer the convention, so the organization of code is very flexible, and our control code can be written inside the Setup.

The setup function provides two parameters: props and context. Importantly, this is missing from the setup function. In Vue3.0, access to them becomes the following: this. XXX = “context.xxx

We have no this context and no enforced code separation of the Options API. The Composition API gives us more scope, so we need to be more careful about making appointments.

For complex logical code, we should pay more attention to the original intention of the Composition API, and do not be afraid to use the Composition API to separate the code and export it into various modules.

Here’s what we expect:

importuseAfrom'./a'
importuseBfrom'./b'
importuseCfrom'./c'
exportdefault{
    setup (props) {
      let{ a, methodsA } = useA()
      let{ b, methodsB } = useA()
      let{ c, methodsC } = useC()
      return{ a, methodsA, b, methodsB, c, methodsC }
    }
}
Copy the code

3: Data () changes to setUp()

Life cycle functions can only be written in setUp

Provide /inject can only be written in setUp

Even as the setup content code gets bigger and bigger, it’s always going to be big, clean and uncluttered.

Conclusion:

First, in VUE 3.0, the life cycle is exported from VUE, and we export what we need to use.

Vue offers so many life cycles, how many are we used to? In most components, we don’t use a life cycle. Even for page-level applications, onMounted is probably the most popular.

Of course, those bind time operations will use unbind, so onUnmounted will be used. The rest of the life cycle, under normal circumstances, is basically not needed.

So, by introducing this configuration, we can reduce the size of our final compiled project. Moreover, such introduction and use, more logical and clear.

Second, with the exception of setup, all lifecycle functions are written directly inside setup.

Ref function

Ref is a function that takes an argument and returns a magical responsive object. The 0 that we initialize is wrapped around this object as a parameter, and changes can be detected in the future and made accordingly.

<template> <h1>{{count}}</h1> <h1>{{double}}</h1> <button @click="increase">+1</button> </template> <script lang="ts"> import { computed, ref, reactive, toRefs } from 'vue' interface DataProps { count: number double: number increase: () => void } export default { name: 'App', setup() { const data:DataProps = reactive({ count: 0, increase: () => { data.count++ }, double: computed(() => data.count * 2) }) const refData = toRefs(data) return { ... refData } } } </script>Copy the code

Reactive function

Reactive function

import { ref, computed, reactive, toRefs } from 'vue' interface DataProps { count: number; double: number; increase: () => void; } setup() { const data: DataProps = reactive({ count: 0, increase: () => { data.count++}, double: computed(() => data.count * 2) }) const refData = toRefs(data) return { ... refData } }Copy the code

Ref or Reactive can be used to choose such criteria

  • First, just like you did with native javascript code, you can choose to use ref or Reactive just like you would if you were writing normal JS code and choosing primitive types and object types.

  • Second, all scenarios use Reactive, but remember to use toRefs to keep the properties of the Reactive object responsive.

Detect changes – watch function

Watch the document

<template> <h1>{{ count }}</h1> <h1>{{ double }}</h1> <button @click="increase">+1</button> <button @click="updateGreeting">updateGreeting</button> </template> <script lang="ts"> import { computed, ref, reactive, toRefs, watch } from 'vue' interface DataProps { count: number double: number increase: () => void } export default{ name: 'app', setup() { const data: DataProps = reactive({ count: 0, increase: () => { data.count++ }, double: computed(() => data.count * 2) }) const greetings = ref('') const updateGreeting = () => { greetings.value += 'Hello' } watch([greetings, () => data.count ], ( newValue, oldValue ) => { console.log(newValue) console.log(oldValue) document.title += 'updated' + greetings.value }) const refData = toRefs(data) return { ... refData, greetings, updateGreeting } } } </script>Copy the code

Watch Simple App

Watch (data, () => {document.title = 'updated '+ data.count}) Watch (refdata. count, (newValue, oldValue) => {console.log('old', oldValue) console.log('new', NewValue) document.title = 'updated '+ data.count}) Watch ([greetings, data], (newValue, oldValue) => {console.log('old', oldValue) console.log('new', NewValue) document.title = 'updated' + greetings.value + data.count} watch([greetings, () => data.count], (newValue, oldValue) => { console.log('old', oldValue) console.log('new', newValue) document.title = 'updated' + greetings.value + data.count })Copy the code

At the end

Lazy people, do not want to map, hope to help you

Public number: small he growth, the Buddha department more text, are their own once stepped on the pit or is learned things

Interested little partners welcome to pay attention to me oh, I was: he Small Life. Everybody progress duck together