SoFunction
Updated on 2025-04-05

Detailed explanation of the example of defining responsive data in Vue combination API-setup

1. Disadvantages of Options API (optional API)

1.1 What is an Optional API

existThe way to write components is to useOptions API, Its characteristic is to write corresponding functional modules in the corresponding properties.

for exampledataDefine data inmethodsDefine methods incomputedDefine the computed properties,watchThe listening attribute changes.

Life cycle hooks also belong toOptions API(OptionalAPI)。

1.2 Disadvantages of Optional API

  • When we implement a certain function, the code logic corresponding to this function will be split into various properties.

When components become large and complex, the list of logical concerns will grow, and the logic of the same function will be split and dispersed.

Especially for those who didn't write these components at the beginning (those who read the components), the code for this component is difficult to read and understand.

  • Fragmented code uses to understand and maintain this complex component and it becomes very difficult to hide potential logic problems.
  • When dealing with a single logical concern, it is necessary to constantly jump to the corresponding code block, increasing the cost of code maintenance.

2. Composition API (combination API) overview

2.1 The role of Composition API

It would be better if the code related to the same logical concern was collected together, and that'sComposition APIThings you want to do.

Vue Composition APICan be referred to asVCA

2.2 The encoding location of the Composition API

ProvidedsetupFunctions to write various combinationsAPI

setupIn fact, it is another option for the component, but this option can be used to replace most other options.APIOptions.

for examplemethodscomputedwatchdata, various life cycle hook functions, etc.

3. Parameters and return value of the setup function

3.1 Parameters of the setup function

The setup function mainly consists of two parameters:

  • props: The properties passed by the parent component will be placed inpropsIn the object
    • propsTypes, and optionsAPIThe same rules in the props option are defined
    • propsThe use oftemplateIt's still possible topropsThe attributes in it are considered ordinaryVueUse variables.
    • existsetupUsed in functionsprops, cannot be passedthisGo and get it
  • context: Also calledSetupContext,yessetupThe context object of a function, which is mainly composed of three properties
    • attrs: All nonpropsProperties of
    • slots: The slot passed by the parent component will be effective when returning as a rendering function
    • emit: When an event is required to be issued within the component, emit will be used
    • Mainly becausesetupNot accessible in the functionthis, so it cannot passthis.$emitPublish an event

3.2 The return value of the setup function

setupThe return value can be used as a substitute fordataOptions, thereforesetupThe return value can be in the templatetemplateUsed in.

<script>
import { ref } from 'vue'

export default {
  setup() {
    // Define the content of the counter    // The data defined by default is not responsive data. Using ref can make the data responsive     let counter = ref(100)
     return {counter}
  }
}
</script>

setupThe return value can be used as a substitute formethodsMethods defined in

<script>
import { ref } from 'vue'

export default {
  setup() {
    // Define the content of the counter    // The data defined by default is not responsive data. Using ref can make the data responsive    let counter = ref(100)
    const increment = () => {
        ++
       ()
    }

	return {counter, increment}

  }
}
</script>

4. How to define responsive data in setup

4.1 reactive function

Code example:

<template>
  <div>
    <h2>account: {{  }}</h2>
    <h2>password: {{  }}</h2>
    <!-- Not usedreactiveFunction time,Click this button,Able to modify data,But it cannot be rendered on the page -->
    <button @click="changeAccount">修改account</button>
  </div>
</template>
<script>
  // 1.Introduce reactive functions  import { reactive } from 'vue'

  export default {
    setup() {

      // 2. Use reactive functions: Define responsive data of complex types      const account = reactive({
        username: "Zhang San",
        password: "666666"
      })
      function changeAccount() {
         = "kobe"
      }
	  // 3. Return the defined data      return {account, changeAccount}
    }
  }
</script>

From the code example, you can know that using the reactive function, you can pay attention to three steps:

  • fromVueIntroducedreactivefunction
  • Make the complex data type to be defined (Object or array) Incomingreactivefunction,reactiveThe return value of the function is responsive data.
  • Forgot to besetupReturns in the function can only be used on the template

Why does the data become reactive after adding the reactive function:

When we usereactiveAfter the function processes our data, it will be collected in dependencies when the data is used again.

When the data changes, all collected dependencies perform corresponding responsive operations.

OptionalAPIIn-housedataThe complex data in the options are also handed over to the bottom layer.reactiveFunctions program their responsive objects.

4.2 ref function

1) Basic use of ref function

reactiveFunctions have restrictions on the type passed in, and they require that the object or array type must be passed in.

If you pass in a basic data type, for exampleStringNumberBooleanWait and you will report a warning:

value cannot be made reactive : xxx

Vue3Provide us with another onereffunction.

refThe function returns a mutable responsive object, which maintains its internal value as a responsive reference, which is alsorefThe origin of the name.

The value inside it isrefofvalueThe properties are maintained, so they are usedrefFunction-defined variables need to be used fromvalueAttribute value.

Code example:

<template>
  <div>
    <!-- By default, intemplateUsed inrefhour, vueIt will be automatically unpacked(Take it outvalue) -->
    <h2>Current count: {{ counter }}</h2>
    <button @click="increment">+1</button>
    <button @click="counter++">+1</button>
  </div>
</template>
<script>
  // 1.Introduce ref function  import { ref } from 'vue'

  export default {
    setup() {

      // Function: Mainly defines simple types of data (you can also define complex types of data)      const counter = ref(0)
      function increment() {
        ++
      }
	  // 3. Return the defined data      return {counter, increment}
    }
  }
</script>

2) Ref shallow unpacking

<template>
  <div>
    <!--ref shallow unpacking (Meaning is torefWhen a variable is placed in another object, there will be two situations below.)-->
    <!-- No need to write when using.value -->
    <h2>Current count: {{  }}</h2>
    <!-- Need to write when modifying.value -->
    <button @click="++">+1</button>
  </div>
</template>
<script>
  // 1.Introduce ref function  import { ref } from 'vue'

  export default {
    setup() {

      // Function: Mainly defines simple types of data (you can also define complex types of data)      const counter = ref(0)
      const info = {counter}
	  // 3. Return the defined data      return {counter}
    }
  }
</script>

Note:

  • Introduced in templatesrefWhen the value defined by the function,VueIt will automatically help us unpack
  • Unpacking isVueAutomatically removerefThe variable defined by the functionvaluevalue
  • Therefore, the user does not need to pass the templateUse the method
  • existsetupInside the function,refThe value defined by the function is arefQuote, so you need to useTo operate it in a way
  • aboutrefshallow unpacking
  • Directly intemplateUsed inrefVariables will be automatically unpacked
  • IfrefThe following situation will be found in a variable in an object
    • When used, it will be automatically unpacked
    • When modifying, no automatic unpacking is performed, so it is necessary to usevalueAttribute to get value

4.3 About how to choose reactive functions and ref functions

1) Scenario where reactive function is selected

  • reactiveThe definition of the function applied to local data. Local data means that this data does not originate from the server.
  • reactiveThere is a certain connection between multiple attributes of complex data defined by functions.
import {reactive} from 'vue'

const user = reactive({
	username: 'Zhang San',
	password: '123456'
})

For example, collecting data in a form is a scenario that is very suitable for using reactive functions.

2) Scenario where ref function is selected

Define local simple types of data

import {ref} from 'vue'

const message = ref('hello ref')

Define the data obtained from the server

import {ref} from 'vue'

const music = ref([])							// Define a local arrayconst serverMusicList = ['Little Star', 'The insects fly']		// Simulate the data obtained from the server = serverMusicList					// Assign data to music variables

This is a saying of experience. Many excellent open source projects are also used in this way. The documentation does not specify what situations are used.

This is actually a problem that programmers should consider by themselves

5. The use of one-way data flow and readonly

5.1 One-way data flow specification

1) What is a one-way data flow specification

The object data passed to the child component by the parent component can only be used and not allowed to be modified.

Although it can be modified, it violates the principle of one-way data flow.

If you really want to modify this data, you should issue an event, let the parent component listen to the event, and then modify it in the parent component.

2) Why follow this principle

In the future, there may be many child components in the project, and one data of the parent component may be passed to multiple child components.

Since it is passed a reference to the data object, modifying the data in one of the subcomponents will cause all references to be affected.

Moreover, it is difficult to know which location of the data was modified during maintenance.

There are many similar concept specifications in other places:

  • reactmiddle
  • reactThere is an important principle: any component should be like a pure function and cannot be modified.props
  • jsmiddle
  • existjsThere are similar principles in it, familiarjsThe concept of a pure function may be known. A pure function means that the function does not modify the passed parameters.

If these specifications are not followed, the code can indeed implement functions. But the maintenance will be very poor in the future, whoever tries will know.

5.2 Readonly use

When passing data to a component, if you want the component to use the passed content. But when they are not allowed to be modified, it can be usedreadonlyNow.

Because the principle of one-way data flow isIt cannot be avoided from the code at any time. If a programmer doesn't know this principle at all.

It is possible to write code that is difficult to maintain.

andProvidedreadonlyFunctions avoid this problem from the encoding level.

<template>
	<!-- Give componentshomePass a read-only data -->
	<home :info="readonlyInfo" />
</template>
<script>
    import { readonly } from 'vue'
    setup() {
      // Locally define multiple data that needs to be passed to subcomponents      const info = reactive({
        name: "Zhang San",
        age: 25,
        height: 1.78
      })

      // Use readOnly to wrap info      const roInfo = readonly(info)
      return {roInfo}
    }
</script>

readonlyThe returned objects are not allowed to be modified; howeverreadonlyThe original object processed is allowed to be modified.

For example, for statementsconst info = readonly(obj)infoObjects are not allowed to be modified.

whenobjWhen modified,readonlyReturnedinfoThe object will also be modified;

But we can't modifyreadonlyReturned objectinfo

If the code itself adheres to the principle of one-way data flow, it can also be used without

Other points of note for readonly:

  • readonlyThe read-only proxy that returns the original object
  • That is, it's still oneProxy, this is aproxyofsetThe method is hijacked and cannot be modified
  • Common in developmentreadonlyThe method will pass in three types of parameters:
  • Type 1: Normal object
  • Type 2:reactiveReturned object
  • Type 3:refObject of

6. Reactive-related judgment API

  • isProxy: Check whether the object isreactiveorreadonlyCreatedproxy
  • isReactive: Check whether the object isreactiveResponsive proxy created
  • If the proxy is readonlyBuilt, but wrapped byreactiveAnother proxy created, it will returntrue
  • isReadonly: Check whether the object isreadonlyA read-only proxy created.
  • toRaw:returnreactiveorreadonlyThe original object of the proxy (Present references to the original object are not recommended. Please use with caution)
  • shallowReactive: Create a responsive proxy that tracks itselfpropertyResponsiveness

But deep responsive transformations of nested objects (deep or native objects).

shallowReadonly: Create aproxy, make its ownpropertyFor read only

But the deep read-only conversion of nested objects is not performed (deeply readable and writable)

These may not be used much, but you should also understand

7. Ref other APIs

7.1 toRefs

useES6deconstructed syntax,reactiveThe returned object is deconstructed to obtain the value, and the data will no longer be responsive.

const info = reactive({
    name: "Zhang San",
    age: 25,
    height: 1.78
})

ES6 deconstruction:

const {name, age, height} = info;

Data loss responsiveness

toRefs deconstruction:

const {name, age, height} = toRefs(info);

The data remains responsive after deconstruction

7.2 unref

Used to obtain arefQuotevalue

  • If the parameter is aref, then return the internal value, otherwise return the parameter itself
  • This is alsoval = isRef(val) ? : valSyntax sugar function 7.3 isRef

Determine whether the value is a ref object.

7.4 shallowRef

Create a shallow layerrefObject.

7.5 triggerRef

Manual trigger andshallowRefCreates a responsive form of an object.

This is the article about the detailed explanation of the Vue combination API-setup definition of responsive data. For more related Vue combination API setup content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!