preface

Last time we looked at Vue3.0’s composite Api, now let’s take a look at Setup.

What is the setup

Setup is a new method in Vue3.0, watch and so on in Vue2.0 become hooks that resolve from Vue

import {watch} from 'vue'

export default {
    setup() {
       watch(() = >{}}}Copy the code

Setup is used to define variables and methods and requires a return template to use. In terms of the lifecycle, setup precedes creation, so this cannot be used. In Vue3.0, to avoid errors, this is undefined in setup and steup receives two parameters, context and props

    setup(props,context) {
        console.log(props)
        console.log(context)
    }
Copy the code

You can see it on the console

Props is wrapped in proxy, so the data in it is reactive and the usage is consistent with Vue2.0. Context contains the attrs, emit, and slot attributes

  • Attrs, as in 2.0, gets properties not defined in props
  • Slots corresponds to component slots, which corresponds to Vue2.0’s this.$slots.
  • Emit corresponds to this.$emit in 2.0
The return value

If setup returns an object, it is incorporated into the Render Context and can be used in the template

setup(props,context) {
   const  count = 0
    return{
       count
    }
}
Copy the code

To return the rendering function, h needs to be introduced

import {ref ,reactive,h} from 'vue'
setup(props,context) {
           const  count = 0
            return() = >h('h1'.'This is a node created by a template function')}Copy the code

The content of this article may be insufficient or there are problems, you are welcome to put forward suggestions, actively respond to the digging activities, this article is participating in the “digging gold pamphlet free learning!” Event, click to view details of the event