Let you quickly master the vue3 tutorial in 30 minutes

  • 2021-09-04 23:20:10
  • OfStack

After a long iteration, Vue 3.0 was finally released on September 18, 2020, with earth-shaking changes. Typescript was used for large-scale reconstruction, bringing Composition API RFC version, writing Vue like React Hook 1, and customizing your own hook to make users more flexible. Next, summarize some new features brought by vue 3.0.

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

Comparison between Vue2 and Vue3

Unfriendly to TypeScript support (all attributes are placed on this objects, which makes it difficult to push down the data types of components) A large number of API are mounted on prototypes of Vue objects, making it difficult to implement TreeShaking. The architecture level is unfriendly to cross-platform dom rendering development support CompositionAPI. Inspired by ReactHook jsx is more convenient to support Template for Vue 3 supports multiple root tags, but not for Vue 2 The virtual DOM is rewritten, and the compilation of templates is optimized...

1. setup function

The setup () function is a new property provided specifically for components in vue 3. It provides an entry for us to use the new features of Composition API of vue3. The setup function will be executed after beforeCreate and before created. vue3 also cancels these two hooks, and the system 1 is replaced by setup, which is equivalent to a life cycle function. All the past data, methods and watch in vue are written in setup () function with corresponding new api


setup(props, context) {
  context.attrs
  context.slots
  context.parent
  context.root
  context.emit
  context.refs
  
  return {
    
  }
 }

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

2. reactive function

reactive () function receives a common object and returns a responsive data object. It is also very simple to use the created responsive data. After it is created, return goes out in setup and can be called directly in 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 according to the given value. The return value of the ref () function call is an object, which contains only one value attribute. It is only necessary to add. value to access the ref function inside the setup function


<template>
  <div class="mine">
    {{count}} // 10
  </div>
</template>

<script lang="ts">
import { defineComponent, ref } from 'vue';
export default defineComponent({
 setup() {
  const count = ref<number>(10)
  //  In js  Get from ref  Values defined in ,  Need to pass value Attribute 
  console.log(count.value);
  return {
    count
  }
  }
});
</script>

Accessing responsive data created by ref in reactive object


<template>
  <div class="mine">
    {{count}} -{{t}} // 10 -100
  </div>
</template>

<script lang="ts">
import { defineComponent, reactive, ref, toRefs } from 'vue';
export default defineComponent({
 setup() {
  const count = ref<number>(10)
  const obj = reactive({
   t: 100,
   count
  })
  //  Pass reactive  To get ref  When the value of , Do not need to use .value Attribute 
  console.log(obj.count);
  return {
    ...toRefs(obj)
  }
  }
});
</script>

4. 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)
  console.log(isRef(age)); // true
  console.log(isRef(name)); // false

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

5. toRefs () Function

The toRefs () function converts a responsive object created by reactive () into an ordinary object, except that every attribute node on this object is responsive data of type ref ()


<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, as in the past 1, and it returns a value of 1 ref object. You can transfer a method or an object, which contains set (), get () methods

6.1 Creating a Read-Only Calculated Property


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

  //  According to  age  To create the value of 1 Calculated properties of responses  readOnlyAge, It will depend on the dependent  ref  Automatically calculate and return 1 A new one  ref
  const readOnlyAge = computed(() => age.value++) // 19

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

6.2 Creation of 1 Readable and Writable Computed Property by set (), get () Methods


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

  const computedAge = computed({
   get: () => age.value + 1,
   set: value => age.value + value
  })
  //  To assign a value to a computed property, triggers  set  Function ,  Trigger  set  Function, age  The value of will be updated 
  age.value = 100
  return {
   age,
   computedAge
  }
 }
});
</script>

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, which means that the callback is executed only when the listening source data changes.

7.1 Listening for data sources declared with reactive


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

  watch(
   () => state.age,
   (age, preAge) => {
    console.log(age); // 100
    console.log(preAge); // 10
   }
  )
  //  Modify age  Triggered when watch  Callback of ,  Print values before and after changes 
  state.age = 100
  return {
   ...toRefs(state)
  }
 }
});
</script>

7.2 Listening for data sources declared with ref


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

  watch(age, () => console.log(age.value)); // 100
  
  //  Modify age  Triggered when watch  Callback of ,  Print the changed value 
  age.value = 100
  return {
   age
  }
 }
});
</script>

7.3 Listening for Multiple Values at the Same Time


<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>

0

7.4 stop Stop Listening

watch monitoring created within the setup () function automatically stops when the current component is destroyed. If you want to explicitly stop a monitoring, you can call the return value of the watch () function, with the following syntax:


<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>

1

8. LifeCycle Hooks (New Late Life)

The new lifecycle function can be imported into components on demand, and can only be used in setup () function, but it can also be defined outside setup and used in setup


<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>

2

9. Template refs

Go back to the real dom element through refs, which is the same as react. In order to get a reference to an element or component instance in the template, we can declare an ref in setup () and return it as usual

As usual, write the name of ref in html
Define 1 ref in steup Returns an instance of ref in steup The RefImpl object of ref can be obtained in onMounted, and the real dom can be obtained through. value

<template>
 <!-- No. 1 1 Step: As usual 1 Sample, in  html  Write in  ref  Name of -->
 <div class="mine" ref="elmRefs">
  <span>1111</span>
 </div>
</template>

<script lang="ts">
import { set } from 'lodash';
import { defineComponent, onMounted, ref } from 'vue';
export default defineComponent({
 setup(props, context) {
  //  Get the truth dom
  const elmRefs = ref<null | HTMLElement>(null);
  onMounted (() => {
   console.log(elmRefs.value); //  Get 1 A  RefImpl  Object of ,  Pass  .value  Access to data 
  })

  return {
   elmRefs
  }
 }
});
</script>

10. Global Configuration of vue

Configured by config on an vue instance, and contains objects for the global configuration of the Vue application. You can modify the properties listed below before mounting the application:


<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>

4

Assign handlers for uncaught errors during component rendering functions and watchers. Errors and application instances call handlers


<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>

5

A global property that can be accessed in any component instance within the application, the component's properties will have priority. This replaces Vue 2. xVue. prototype extension:


<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>

6

You can use getCurrentInstance () to get the configuration information in the global globalProperties, the getCurrentInstance method to get the instance of the current component, and then use the ctx property to get the current context, so that we can use router and vuex in setup, through which we can manipulate variables, global properties, component properties, and so on


<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>

7

101. Suspense Components

Before we begin to introduce the Suspense component of Vue, it is necessary to understand the Suspense component of React under 1, because their functions are similar.

React. lazy accepts a function that calls import () dynamically. It must return an Promise, which requires an React component of an resolve and an default and an export.


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

Vue3 also adds an defineAsyncComponent function with similar functionality to React. lazy to handle dynamic introduction. defineAsyncComponent can accept factory functions that return commitments. When you retrieve the component definition from the server, you should call the parse callback of Promise. You can also call reject (reason) to indicate that the load has failed


<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>

9

Vue3 also adds the 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>

102. vue 3. x Complete Component Template Structure

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


<template>
 <div class="mine" ref="elmRefs">
  <span>{{name}}</span>
  <br>
  <span>{{count}}</span>
  <div>
   <button @click="handleClick"> Test button </button>
  </div>

  <ul>
   <li v-for="item in list" :key="item.id">{{item.name}}</li>
  </ul>
 </div>
</template>

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

interface IState {
 count: 0,
 name: string,
 list: Array<object>
}

export default defineComponent({
 name: 'demo',
 //  Parent component passes child component parameters 
 props: {
  name: {
   type: String as PropType<null | ''>,
   default: 'vue3.x'
  },
  list: {
   type: Array as PropType<object[]>,
   default: () => []
  }
 },
 components: {
  /// TODO  Component registration 
 },
 emits: ["emits-name"], //  In order to prompt the effect, 
 setup (props, context) {
  console.log(props.name)
  console.log(props.list)
  
  
  const state = reactive<IState>({
   name: 'vue 3.0  Component ',
   count: 0,
   list: [
    {
     name: 'vue',
     id: 1
    },
    {
     name: 'vuex',
     id: 2
    }
   ]
  })

  const a = computed(() => state.name)

  onMounted(() => {

  })

  function handleClick () {
   state.count ++
   //  Invoke the method of the parent component 
   context.emit('emits-name', state.count)
  }
 
  return {
   ...toRefs(state),
   handleClick
  }
 }
});
</script>

Ecology of vue 3

Official website Source code vite Builder Scaffolding: https://cli.vuejs.org/ vue-router-next vuex4.0

UI Component Library

vant2.x

Ant Design of Vue 2.x

element-plus


Related articles: