“This is the 10th day of my participation in the November Gwen Challenge. See details of the event: The Last Gwen Challenge 2021”.

preface

Last time we reviewed the important points of VUE2.

What’s updated with VUe3

The main changes are:

  • New features of the combined API
  • The global Vue API has been changed to use application instances
  • The global and internal apis have been refactored to support tree-shake
  • You can only create components using normal functions
  • Filter removal
  • For other complete changes, check out the official link

Combination of API – the Setup

Setup accepts two parameters: props Context 2. The arrays, methods, and so on used by components are configured in setup. 3. If setup returns an object, the property of that object and the property in the props argument passed to setup are accessible in the template. Such as:

export default { props: { collectionName: String }, setup(props) { const readersNumber = ref(0) const book = reactive({ title: 'Vue 3 Guide'}) // Exposed to template return {readersNumber, book}}}Copy the code

This means that readersNumber and book can be accessed in the code. Of course, the previous data writing method can also be used, but it is best not to use together.

Setup can also return a render function that directly uses the reactive state declared in the same scope:

Import {h} from 'vue' export default {setup() {return () => h('div', 'hello! ')}}Copy the code

It simply renders a

hello

and invalidates the DOM in scope.

Composite API- Lifecycle hooks

Because setup runs around beforeCreate and Created lifecycle hooks, any code written in these hooks should be written directly in the setup function as an “on-hook function name.” For example: Mounted

// MyBook.vue export default { setup() { // mounted onMounted(() => { console.log('Component is mounted! ')})}}Copy the code

BeforeCreate and beforeCreate are Not needed – Hook inside setup.

Combined API-Provide/Inject

Provide: indicates the provider. 2. It’s a core investment. Provide/Inject is mainly used for communication of multi-level components

For example, we first Provide through Provide.

<! -- src/components/MyMap.vue --> <template> <MyMarker /> </template> <script> import { provide } from 'vue' import MyMarker from './MyMarker.vue' export default { components: { MyMarker }, setup() { provide('zhangsan', { age: 21, sex: 1 }) } } </script>Copy the code

Use inject: The inject function takes two arguments:

  • The name of the property to inject
  • Default value (Optional)

Then we receive it through Inject

<! -- src/components/MyMarker.vue --> <script> import { inject } from 'vue' export default { setup() { const zhangsan = inject('zhangsan') return { zhangsan } } } </script>Copy the code

It’s that simple

At the end

All right, it’s 23:00 tomorrow.