Combine apI-setup functions

role

Setup is a new component option that serves as a starting point for using composite apis in components.

  1. The setup function is a new component option that serves as a starting point (entry) for the composite API in the component
  2. Setup cannot use this; this points to undefined
  3. The setup function is executed only once when the component is initialized
  4. The setup function is executed before the beforeCreate lifecycle hook is executed

Execution time

Execute before component instance creation (before beforeCreate)

setup() {
	console.log('setup.... '.this)},beforeCreate() {
	console.log('beforeCreate') // It is later than setup
}
Copy the code

This is not yet a component instance in the setup function; this is undefined at this point

parameter

// The first parameter is props. Props is an object that contains all prop data passed by the parent component
// The second argument is an object context. The context object contains the attrs, slots, emit attributes,
setup(props, context){}Copy the code

The return value

The return value of this function is an object in which the data and functions used in the template need to be declared.

If data with the same name is also defined in data(), setup() prevails.

Demo code

<template>
  <div class="container">Name :{{name}} salary :{{salary}}<button @click="say">Say hello</button>
  </div>
</template>
<script>
export default {
  setup () {
    console.log('Setup executes')
    console.log(this)
    // Define data and functions
    const name = 'xiao wu'
    const salary = 18000
    const say = () = > {
      console.log('I am', name)
    }

    return { msg , say}
  },
  beforeCreate() {
    console.log('beforeCreate executed ')
    console.log(this)}}</script>
Copy the code

summary

  • Setup is executed before beforeCreate
  • Setup cannot be accessed with this, which returns undefined
  • The return value format of setup is an object