This article is based on VUe3.2. It mainly discusses the new features of VUe3 and the differences between vuE2 and VUE3, including the responsive Api, composition Api, and setup syntax sugar. See v3.cn.vuejs.org/ for more information on template syntax, list rendering, and conditional judgment

Vue3 window

  1. Nearly twice as fast as vue
  2. Tree Shaking compiles code on demand
  3. Composition API for better logic reuse and code organization
  4. Better type inference (typeScript support)

Application gateways

  1. createApp()Function to create an application instance, import the function in vUE
  2. mount()Function to mount the application root component
/ / the main reference. Js
import { createApp } from 'vue'
import App from './App.vue'

createApp(App).mount('#app')
Copy the code
  1. Use plug-ins by chain operation
import router from './router/index'
import element3 from '@/plugins/element3.js'
// ...
createApp(App).use(router).use(element3).mount('#app')
Copy the code

Responsiveness API

  1. Reactive: Objects are reactive

A responsive proxy that takes a normal object and returns that normal object. Vue.observable() equivalent to vue 2.x

import { reactive } from 'vue'
const obj = reactive({ count: 0 })
Copy the code
  1. Ref: single-valued response

Accepts a parameter value and returns a reactive Ref object. The Ref object has a single attribute value that points to an internal value.

const count = ref(0)
console.log(count.value) / / 0

count.value++
console.log(count.value) / / 1
Copy the code

{{count}} can be used directly in templates, templates will be automatically unpacked. Add.value to the template only when accessing nested refs.

  1. ToRefs method

Convert a reactive object into a normal object where each attribute is a Ref.

const state = reactive({
    foo: 1.bar: 2,})const stateAsRefs = toRefs(state)
Copy the code

When using ES6 structured reactive objects, the responsivity of the deconstructed property is lost. In this case, you can use the toRefs method to prevent reactive loss.

const book = reactive({
  author: 'Vue Team'.year: '2020'.title: 'Vue 3 Guide'.description: 'You are reading this book right now ;) '.price: 'free'
})

// let {author, title} = book
let { author, title } = toRefs(book)

title.value = 'Vue 3 Detailed Guide' // We need to use.value as the title, now ref
console.log(book.title) // 'Vue 3 Detailed Guide'
Copy the code

Tips Some of the above apis need to be imported first.

Modular API

Vue2 uses the Options API and VUe3 uses the composition API. Composite apis A set of less intrusive, functional apis that allow us to “compose” a component’s logic more flexibly. It avoids the problem of repeatedly skipping logical blocks in optional apis.

1. setup

A component option that is executed after the props is resolved before the component is created. It is the entry point to a composite API. You can’t use this in setup, and you don’t need to.

import { onMounted } from 'vue'
export default {
  components: { Temp },
  props: {
    user: {
      type: String.required: true}},setup(props) {
    console.log(props) // { user: '' }
    // Lifecycle hooks
    onMounted(() = > {
      console.log('Component is mounted! ')})return {} // Anything returned here can be used for the rest of the component
  }
  // The "rest" of the component
}
Copy the code

Prior to vue3.2 some of the apis and lifecycle functions were written in the setup method. A setup sugar

2. <script setup> syntax sugar

It has many advantages over plain

  • Less boilerplate content, cleaner code.
  • You can declare props and throw events using pure Typescript.
  • Better runtime performance (their templates are compiled into renderers of the same scope as them, without any intermediate proxies).
  • Better IDE type inference performance (less work for the language server to extract types from code).

Here’s how to use it:

  • To use this syntax, change thesetupThe attribute is added to the<script>On the code block:
<script setup>
    const msg = 'hello world! ';
</script>
Copy the code

The code inside is compiled into the contents of the component setup() function. This means that instead of normal

  • The top-level bindings of declarations (including variables, function declarations, and import imports) can be used directly in templates:
<template>
    <p> {{ msg }} </p>
</template>
Copy the code
  • responsive
<script setup>
const count = ref(0)
function addcount() {
  count.value++
}
</script>
Copy the code
  • Using the component
<template>
   <Foo />
</template>
<script setup>
    import Foo from './components/Foo.vue'
</script>
Copy the code

3. defineProps 和 defineEmits

DefineProps and defineEmits apis must be used to declare props and emits in

Child components

<template>
  <div class="box">
    <p>I'm a Foo component</p>
    <button @click="add">{{ num }}</button>
  </div>
</template>

<script setup>
const props = defineProps({
  num: Number,})// console.log(props)
const emits = defineEmits(['add'])
// console.log(emits)

function add() {
  emits('add')}</script>
Copy the code

The parent component

<Foo :num="num" @add="add" />

<script setup>
const num = ref(100)
const add = () = > {
  num.value++
}
</script>
Copy the code

DefineProps and defineEmits are compiler macros that can only be used in

4. Life cycle

You can register lifecycle hooks by importing the onX function directly:

<script setup>
import { onMounted, onUpdated } from 'vue'

onMounted(() = > {
  console.log('Component is mounted! -- -- -- -- -- -- -- -- -- -- -- -- -- ')
})
onUpdated(() = > {
  console.log('updated! ----------------num', num.value)
})
</script>
Copy the code

Mapping between the lifecycle options of the optional API and the composite API

  • beforeCreate– > usesetup()
  • created– > usesetup()
  • beforeMount -> onBeforeMount
  • mounted -> onMounted
  • beforeUpdate -> onBeforeUpdate
  • updated -> onUpdated
  • beforeUnmount -> onBeforeUnmount
  • unmounted -> onUnmounted
  • errorCaptured -> onErrorCaptured
  • renderTracked -> onRenderTracked
  • renderTriggered -> onRenderTriggered
  • activated -> onActivated
  • deactivated -> onDeactivated

Evaluate properties and listeners

  • Computed returns a REF object that cannot be changed manually.
const plusOne = computed(() = > count.value + 1);
plusOne.value++; // error
Copy the code
  • The listener watch

Frames listen to a single data source

// Listen for a getter
const state = reactive({ count: 0 })
watch(
  () = > state.count,
  (count, prevCount) = > {
    / *... * /})// listen on ref directly
const count = ref(0)
watch(count, (count, prevCount) = > {
  / *... * /
})
Copy the code

Watch can also listen to multiple data sources using array frames

watch([fooRef, barRef], ([foo, bar], [prevFoo, prevBar]) = > {})
Copy the code
  • The Side effect listener, watchEffect

Execute a function passed in immediately, collect reactive dependencies, and re-run the function when the dependency changes.

watchEffect(() = > console.log(count.value)) // Initial execution prints 0
Copy the code

This article demo address github.com/kongcodes/v…

Vue3 project construction started from 0