SoFunction
Updated on 2025-04-06

Detailed explanation of the role example of Vue3 setup

Upgrading vue3 from vue2, vue3 is compatible with vue2. Therefore, vue3 can adopt the option API of vue2, but vue2 cannot use the combined API of vue3.

Since an option API exists in multiple places, if problems arise, you need to cover multiple functions. The bigger the project, the more difficult it is to investigate.

How to use setup:

setup is used to write a combination API, which is equivalent to replacing beforeCreate() from the perspective of life cycle.

How to use the data and methods of setup?

(){} The properties and methods inside must be exposed with return.

Mount the attribute on the instance, otherwise there is no way to use it.
Syntax sugar: written in script start tag, internal properties and methods without return exposure;
Cannot be mixed with the option API.

When used internally, there is no this

3. The hook function can exist side by side with setup

Lifecycle-related functions cannot be called, or nested exist.

5. Lifecycle-related functions can call setup-related properties and methods

6. This can be used

setup parameters

When using setup, it will receive two parameters: props and context

props:

  • Indicates the data passed by the parent component to the child component;
  • Props are responsive and are automatically updated when data changes
  • Because props are responsive, Es6's deconstruction cannot be used, if used, it will eliminate the responsive feature (using toRefs)

context:

Context environment. It includes three parts: properties, slots, and custom events.

  • attrs: is a non-responsive object that mainly accepts no-props (non-props) attributes. Often used to pass some style/tag specific attributes.
  • slots: is a Proxy object where () gets an array. The length of the array indicates the number of slots, and the elements in the array are the contents of the slots.
  • emit: Because there is no this in the setup, use emit to replace the previous this.$emit('custom event name', value passed). Used to trigger custom events when children pass through parent
  • Example: emit('custom event name', value passed)

Setup Feature Summary:

  • This function will be executed before created.
  • There is no this inside the setup, and this related stuff cannot be mounted
  • The properties and methods inside the setup must be exposed. (Not required in syntax sugar)
  • None of the properties inside the setup are responsive;
  • setup cannot call lifecycle-related functions, but lifecycle-related functions can call setup

Use of setup in code

<script>
import { onMounted, toRefs } from "vue";
export default {
  props: {
    msg: "abc",
  },
  setup(props, context) {
    let { msg } = toRefs(props);
    let { attrs, slots, emit } = context;
    (props, context);
    let num = 10;
    return {
      num,
    };
    // and setup, nested life cycle    // onMounted(() => {
    //   ("onMounted", num);
    // });
  },
  // Life cycle parallel to setup  mounted() {
    ("After mount");
    (this.$options);
  },
  data() {
    return {};
  },
  methods: {},
};
</script>

Summarize:

The above is the role of setup in vue3.

Knowledge point expansion:

Function and implementation of setup function in Vue3

  • The setup function is a new component option added to vue3, and its function is

  • The ability to establish combination logic, create responsive data, create general functions, and register life cycle hooks with combined APIs
  • The setup function will only be executed when it is mounted
  • There are two types of setup return value
  • function
  • Object
  • If it is an object, the data contained in the object is exposed to the template.
  • Take the setup from the component in the function that renders the component, get the return value of its execution, determine whether it is a function, and mount it on the component instance
  • If it is a function, then assign the value to
  • If it is an object, it becomes a responsive form and assigns a value to
export function setupComponent(instance){
    let { type,props,children}  = 
    let {data,render,setup} = type
    //Initialize attributes    initProps(instance,props);
     = new Proxy(instance,instanceProxy);
    if(data){
        if(!isFunction(data)){
            return ('The data option must be a function.')
        }
        //Give the instance data attribute         = reactive(({}))
    }
    if(setup){
      //The second parameter of setup, including emit, attrs, slots, etc.      const context = {}
      const setupResult = setup(,context)
      if(isFunction(setupResult)){
         = setupResult
      }else if(isObject(setupResult)){
         = proxyRefs(setupResult)
      }
    }
    if(!){
      if(render){
       = render

      }else {
        //Template Compilation      }
    } 
}

At the same time, the instance's data proxy makes a listening to setupState

const instanceProxy = {
    get(target,key){
        const { data,props,setupState} = target
        if(data && hasOwn(data,key)){
            return data[key]
        }else if(setupState && hasOwn(setupState,key)){
          return setupState[key]
        }
        else if(props && hasOwn(props,key)){
            return props[key]
        }
        let getter = publicProperties[key]
        if(getter){
            return getter(target)
        }
    },
    set(target,key,value,receiver){
        // debugger
        const {data,props,setupState} = target
        if(data && hasOwn(data,key)){
            data[key] = value
        }else if( setupState && hasOwn(setupState,key)){
            setupState[key]  = value
        }
        else if(props && hasOwn(props,key)){
            ('props not update');
            return false
        }
        return true
    }
}

This is the end of this article about the role of Vue3 setup. For more information about the role of Vue3 setup, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!