SoFunction
Updated on 2025-03-04

Let you quickly master the vue3 tutorial in 30 minutes

After a long iteration, Vue 3.0 was finally released on September 18, 2020, bringing earth-shaking changes, using Typescript for large-scale reconstruction, bringing the Composition API RFC version, writing Vue like React Hook, you can customize your own hooks to make users more flexible. Next, let’s summarize some of the new features brought by vue 3.0.

  • setup()
  • ref()
  • reactive()
  • isRef()
  • toRefs()
  • computed()
  • watch()
  • LifeCycle Hooks (New Lifecycle)
  • Template refs
  • globalProperties
  • Suspense

Vue2 vs. Vue3

  • TypeScript support is not friendly (all attributes are placed on this object, making it difficult to knock down the component's data type)
  • A large number of APIs are mounted on the prototype of Vue object, making TreeShaking difficult to implement.
  • The architecture level is not friendly to cross-platform dom rendering development support
  • CompositionAPI. Inspired by ReactHook
  • More convenient support for jsx
  • Vue 3's Template supports multiple root tags, Vue 2 does not support it
  • The virtual DOM was rewrite and the template was compiled optimized...

1. setup function

The setup() function is a new property specifically provided for components in vue3. It provides a unified entry for us to use the new Composition API feature of vue3. The setup function will be executed after beforeCreate and before created. vue3 also cancels these two hooks and uses setup instead. This function is equivalent to a life cycle function. The past data, methods, watch, etc. in vue are all written in the setup() function with the corresponding new API.

setup(props, context) {
  
  
  
  
  
  
  
  return {
    
  }
 }

  • props: Used to receive props data
  • context is used to define the context. The context object contains some useful properties. These properties need to be accessed through this in vue. This cannot be accessed in the setup() function. It is an undefined
  • Return value: return {}, return responsive data, functions that need to be used in the template

2. Reactive function

The reactive() function receives a normal object and returns a reactive data object. It is also very simple to use the reactive data created. After it is created, return it in the setup and call it directly in the template.

<template>
 {{name}} // test
<template>

<script lang="ts">
import { defineComponent, reactive, ref, toRefs } from 'vue';
export default defineComponent({
 setup(props, context) {
 
  let state = reactive({
   name: 'test'
  });
  
  return state
 }
});
</script>

3. Ref() function

The ref() function is used to create a responsive data object based on the given value. The return value of the ref() function call is an object, which only contains a value attribute. Only when accessing the ref function inside the setup function requires adding a value.

&lt;template&gt;
  &lt;div class="mine"&gt;
    {{count}} // 10
  &lt;/div&gt;
&lt;/template&gt;

&lt;script lang="ts"&gt;
import { defineComponent, ref } from 'vue';
export default defineComponent({
 setup() {
  const count = ref&lt;number&gt;(10)
  // Get the value defined in ref in js, and you need to pass the value attribute  ();
  return {
    count
  }
  }
});
&lt;/script&gt;

Access reactive data created by ref in reactive object

&lt;template&gt;
  &lt;div class="mine"&gt;
    {{count}} -{{t}} // 10 -100
  &lt;/div&gt;
&lt;/template&gt;

&lt;script lang="ts"&gt;
import { defineComponent, reactive, ref, toRefs } from 'vue';
export default defineComponent({
 setup() {
  const count = ref&lt;number&gt;(10)
  const obj = reactive({
   t: 100,
   count
  })
  // When obtaining the value of ref through reactive, there is no need to use the .value attribute  ();
  return {
    ...toRefs(obj)
  }
  }
});
&lt;/script&gt;

IV. isRef() function

isRef() is used to determine whether a value is an object created by ref()

<script lang="ts">
import { defineComponent, isRef, ref } from 'vue';
export default defineComponent({
 setup(props, context) {
  const name: string = 'vue'
  const age = ref<number>(18)
  (isRef(age)); // true
  (isRef(name)); // false

  return {
   age,
   name
  }
 }
});
</script>

5. toRefs() function

The toRefs() function can convert the reactive object created by reactive() into a normal object, but each attribute node on this object is ref() type reactive data

<template>
 <div class="mine">
  {{name}} // test
  {{age}} // 18
 </div>
</template>

<script lang="ts">
import { defineComponent, reactive, ref, toRefs } from 'vue';
export default defineComponent({
 setup(props, context) {
  let state = reactive({
   name: 'test'
  });

  const age = ref(18)
  
  return {
   ...toRefs(state),
   age
  }
 }
});
</script>

6. computed()

This function is used to create computed properties, and as in the past, the value it returns is a ref object. You can pass a method, or an object, which contains set() and get() methods.

6.1 Create read-only computed properties

import { computed, defineComponent, ref } from 'vue';
export default defineComponent({
 setup(props, context) {
  const age = ref(18)

  // Create a responsive computed property readOnlyAge according to the value of age, which will automatically calculate based on the dependent ref and return a new ref  const readOnlyAge = computed(() =&gt; ++) // 19

  return {
   age,
   readOnlyAge
  }
 }
});
&lt;/script&gt;

6.2 Create a readable and writable computational attribute through the set() and get() methods

&lt;script lang="ts"&gt;
import { computed, defineComponent, ref } from 'vue';
export default defineComponent({
 setup(props, context) {
  const age = ref&lt;number&gt;(18)

  const computedAge = computed({
   get: () =&gt;  + 1,
   set: value =&gt;  + value
  })
  // The operation of assigning values ​​to the calculation attribute will trigger the set function. After the set function is triggered, the value of age will be updated.   = 100
  return {
   age,
   computedAge
  }
 }
});
&lt;/script&gt;

7. Watch() function

The watch function is used to listen for a specific data source and perform side effects in the callback function. By default, it is lazy to execute, which means that the callback is executed only when the source data is being listened to.

7.1 Listen to data sources declared using reactive

&lt;script lang="ts"&gt;
import { computed, defineComponent, reactive, toRefs, watch } from 'vue';
interface Person {
 name: string,
 age: number
}
export default defineComponent({
 setup(props, context) {
  const state = reactive&lt;Person&gt;({ name: 'vue', age: 10 })

  watch(
   () =&gt; ,
   (age, preAge) =&gt; {
    (age); // 100
    (preAge); // 10
   }
  )
  // When modifying the age, the callback of the watch will be triggered, and the values ​​before and after the change will be printed.   = 100
  return {
   ...toRefs(state)
  }
 }
});
&lt;/script&gt;

7.2 Listen to data sources declared with ref

&lt;script lang="ts"&gt;
import { defineComponent, ref, watch } from 'vue';
interface Person {
 name: string,
 age: number
}
export default defineComponent({
 setup(props, context) {
  const age = ref&lt;number&gt;(10);

  watch(age, () =&gt; ()); // 100
  
  // When modifying the age, the callback of the watch will be triggered, and the changed value will be printed.   = 100
  return {
   age
  }
 }
});
&lt;/script&gt;

7.3 Listen to multiple values ​​at the same time

&lt;script lang="ts"&gt;
import { computed, defineComponent, reactive, toRefs, watch } from 'vue';
interface Person {
 name: string,
 age: number
}
export default defineComponent({
 setup(props, context) {
  const state = reactive&lt;Person&gt;({ name: 'vue', age: 10 })

  watch(
   [() =&gt; , () =&gt; ],
   ([newName, newAge], [oldName, oldAge]) =&gt; {
    (newName);
    (newAge);

    (oldName);
    (oldAge);
   }
  )
  // When modifying the age, the callback of the watch will be triggered, and the values ​​before and after the change are printed. At this time, you need to pay attention to changing one of the values ​​and the callback of the watch will be executed.   = 100
   = 'vue3'
  return {
   ...toRefs(state)
  }
 }
});
&lt;/script&gt;

7.4 stop Stop listening

Watch monitoring created in the setup() function will automatically stop when the current component is destroyed. If you want to explicitly stop a monitoring, you can call the return value of the watch() function. The syntax is as follows:

&lt;script lang="ts"&gt;
import { set } from 'lodash';
import { computed, defineComponent, reactive, toRefs, watch } from 'vue';
interface Person {
 name: string,
 age: number
}
export default defineComponent({
 setup(props, context) {
  const state = reactive&lt;Person&gt;({ name: 'vue', age: 10 })

  const stop = watch(
   [() =&gt; , () =&gt; ],
   ([newName, newAge], [oldName, oldAge]) =&gt; {
    (newName);
    (newAge);

    (oldName);
    (oldAge);
   }
  )
  // When modifying the age, the callback of the watch will be triggered, and the values ​​before and after the change are printed. At this time, you need to pay attention to changing one of the values ​​and the callback of the watch will be executed.   = 100
   = 'vue3'

  setTimeout(()=&gt; { 
   stop()
   // When modifying at this time, the watch callback will not be triggered    = 1000
    = 'vue3-'
  }, 1000) // In 1 second, the watch will be canceled.  
  return {
   ...toRefs(state)
  }
 }
});
&lt;/script&gt;

8. LifeCycle Hooks (New late life)

The new version of the lifecycle function can be imported into the component as needed and can only be used in the setup() function, but it can also be defined outside the setup and used in the setup

<script lang="ts">
import { set } from 'lodash';
import { defineComponent, onBeforeMount, onBeforeUnmount, onBeforeUpdate, onErrorCaptured, onMounted, onUnmounted, onUpdated } from 'vue';
export default defineComponent({
 setup(props, context) {
  onBeforeMount(()=> {
   ('beformounted!')
  })
  onMounted(() => {
   ('mounted!')
  })

  onBeforeUpdate(()=> {
   ('beforupdated!')
  })
  onUpdated(() => {
   ('updated!')
  })

  onBeforeUnmount(()=> {
   ('beforunmounted!')
  })
  onUnmounted(() => {
   ('unmounted!')
  })

  onErrorCaptured(()=> {
   ('errorCaptured!')
  })

  return {}
 }
});
</script>

9. Template refs

Go back and forth through refs, this is the same as the usage of react. In order to obtain a reference to an element or component instance within the template, we can declare a ref in setup() as usual and return it

  • As usual, write the name of ref in html
  • Define a ref in steup
  • The instance that returns ref in steup
  • You can get the RefImpl object of ref in onMounted, and get the real dom through .value
&lt;template&gt;
 &lt;!--first step:Still as usual,exist html Write in ref Name of--&gt;
 &lt;div class="mine" ref="elmRefs"&gt;
  &lt;span&gt;1111&lt;/span&gt;
 &lt;/div&gt;
&lt;/template&gt;

&lt;script lang="ts"&gt;
import { set } from 'lodash';
import { defineComponent, onMounted, ref } from 'vue';
export default defineComponent({
 setup(props, context) {
  // Get the real dom  const elmRefs = ref&lt;null | HTMLElement&gt;(null);
  onMounted (() =&gt; {
   (); // Get a RefImpl object, access the data through .value  })

  return {
   elmRefs
  }
 }
});
&lt;/script&gt;

10. Global configuration of vue

Configuring it through config on the vue instance, it contains the global configuration of the Vue application. You can modify the properties listed below before mounting the application:

const app = ({})

 = {...}

Assign handlers for uncaught errors during component rendering functionality and observations. Errors and application instances will call handlers

 = (err, vm, info) => {}

Global attributes that can be accessed in any component instance within the application, and the properties of the component will have priority. This can be used instead of the Vue extension:

const app = ({})

.$http = 'xxxxxxxxs'

You can use getCurrentInstance() to obtain the configuration information in global globalProperties in the component. The getCurrentInstance method gets the instance of the current component, and then gets the current context through the ctx property. In this way, we can use router and vuex in the setup. Through this property, we can operate variables, global properties, component properties, etc.

setup( ) {
 const { ctx } = getCurrentInstance();
 ctx.$http  
}

11. Suspense component

Before we begin introducing Vue's Suspense component, it is necessary to understand React's Suspense component because they have similar functions.

Accept a function, which requires a dynamic call to import(). It must return a Promise that requires resolve a React component of default export.

import React, { Suspense } from 'react';
 
 
const myComponent = (() => import('./Component'));
 
 
function MyComponent() {
 return (
  <div>
   <Suspense fallback={<div>Loading...</div>}>
    <myComponent />
   </Suspense>
  </div>
 );
}

Vue3 also added a defineAsyncComponent function with similar functions to handle dynamically introduced (components). defineAsyncComponent can accept factory functions that return promises. When you retrieve the component definition from the server, the parsing callback of the Promise should be called. You can also call reject(reason) to indicate that the load has failed

import { defineAsyncComponent } from 'vue'

const AsyncComp = defineAsyncComponent(() =>
 import('./components/')
)

('async-component', AsyncComp)

Vue3 also has a new Suspense component:

<template>
 <Suspense>
  <template #default>
   <my-component />
  </template>
  <template #fallback>
   Loading ...
  </template>
 </Suspense>
</template>

<script lang='ts'>
 import { defineComponent, defineAsyncComponent } from "vue";
 const MyComponent = defineAsyncComponent(() => import('./Component'));

export default defineComponent({
  components: {
   MyComponent
  },
  setup() {
   return {}
  }
})

</script>

12. vue complete component template structure

A completed vue complete component template structure includes: component name, props, components, setup(hooks, computed, watch, methods, etc.)

&lt;template&gt;
 &lt;div class="mine" ref="elmRefs"&gt;
  &lt;span&gt;{{name}}&lt;/span&gt;
  &lt;br&gt;
  &lt;span&gt;{{count}}&lt;/span&gt;
  &lt;div&gt;
   &lt;button @click="handleClick"&gt;Test button&lt;/button&gt;
  &lt;/div&gt;

  &lt;ul&gt;
   &lt;li v-for="item in list" :key=""&gt;{{}}&lt;/li&gt;
  &lt;/ul&gt;
 &lt;/div&gt;
&lt;/template&gt;

&lt;script lang="ts"&gt;
import { computed, defineComponent, getCurrentInstance, onMounted, PropType, reactive, ref, toRefs } from 'vue';

interface IState {
 count: 0,
 name: string,
 list: Array&lt;object&gt;
}

export default defineComponent({
 name: 'demo',
 // Parent component passes child component parameters props: {
  name: {
   type: String as PropType&lt;null | ''&gt;,
   default: ''
  },
  list: {
   type: Array as PropType&lt;object[]&gt;,
   default: () =&gt; []
  }
 },
 components: {
  /// TODO component registration },
 emits: ["emits-name"], // To prompt setup (props, context) {
  ()
  ()
  
  
  const state = reactive&lt;IState&gt;({
   name: 'vue 3.0 component',
   count: 0,
   list: [
    {
     name: 'vue',
     id: 1
    },
    {
     name: 'vuex',
     id: 2
    }
   ]
  })

  const a = computed(() =&gt; )

  onMounted(() =&gt; {

  })

  function handleClick () {
    ++
   // Call the parent component method   ('emits-name', )
  }
 
  return {
   ...toRefs(state),
   handleClick
  }
 }
});
&lt;/script&gt;

The ecology of vue 3

  • Official website
  • Source code
  • vite builder
  • scaffold:/
  • vue-router-next
  • vuex4.0

UI Component Library

Ant Design of Vue

element-plus

This is the end of this article about allowing you to quickly master the vue3 tutorial in 30 minutes. For more related vue3 introduction content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!