Detailed explanation of the use of Vue's new built-in components

Detailed explanation of the use of Vue's new built-in components

1. Teleport

Teleport Official Documentation

1.1 Introduction to Teleport

1. Vue encourages us to build our UI by encapsulating UI and related behaviors into components. We can nest them within each other to build the tree that makes up our application's UI.

2. However, sometimes part of a component template logically belongs to that component, and from a technical point of view, it is better to move this part of the template to another place in the DOM, that is, outside the Vue application.

Does the above look confusing? It is actually translated from the official document.

In fact, my understanding of Teleport is to mount a component outside the Vue app. As we know, Vue is a SPA (single page) application. All rendering is in the tag with id app. In this case, we create a component at the same level as app and reference it through the teleport tag, so that it can be used on any page.

1.2 Using Teleport

1. We also implement a global modal box here

2. Use the teleport mounting feature through the parent-child component communication mechanism

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <link rel="icon" href="/favicon.ico" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Vite App</title>
  </head>
  <body>
    <div id="app"></div>
    <div id="modal"></div> <!-- Define a tag modal at the same level as app -->
    <script type="module" src="/src/main.ts"></script>
  </body>
</html>

Define a Modal component

<template>
	<!-- teleport has a to attribute, which is attached to the tag with id modal -->
    <teleport to="#modal">
        <div id="center" v-if="isOpen">
            <div class="modal-header" v-if="title">
                <h2>{{ title }}</h2>
                <hr />
            </div>
            <div class="modal-content">
                <!-- We use slots to support external content insertion-->
                <slot></slot>
            </div>
            <button @click="buttonClick">Close</button>
        </div>
    </teleport>
</template>
<script lang="ts">
// defineProps<{ msg: string }>() Vue3 setup defines props
import { defineComponent } from 'vue';
export default defineComponent({
    props: {
        isOpen: Boolean,
        title: String
    },
    // Verify emits: {
        'close-modal': null
        // (payload: any) => {
        // return payload.type === 'close'
        // }
    },
    setup(props, context) {
        const buttonClick = () => {
            context.emit('close-modal');
        }
        return {
            buttonClick
        }
    }
});
</script>
<style>
#center {
    width: 200px;
    height: 200px;
    border: 2px solid black;
    background-color: white;
    position: fixed;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
}
</style>

3. Use Modal component

<script setup lang="ts">
import { ref } from 'vue';
import Modal from './components/Modal.vue';
const modalTitle = ref('Hello, World');
const modalIsOpen = ref(false);
const openModal = () => {
  modalIsOpen.value = true;
}
const onModalClose = () => {
  modalIsOpen.value = false;
}
</script>
<template>
  <img alt="Vue logo" src="./assets/logo.png" />
  <div class="test-useURLLoader">
    <button @click="openModal">modal</button>
    <Modal :title="modalTitle" :isOpen="modalIsOpen" @close-modal="onModalClose">
      My model
    </Modal>
  </div>
</template>
<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

1.3 Preview Effect

Please add a description of the image

2. Suspense

Suspense Official Documentation

Waring : As an experimental feature in Vue3, it may be modified at any time, so it is not recommended for use in production environments.

2.1 Introducing Suspense

It can be used for asynchronous data. It has a local processing method to adapt to various situations and provides two choices (slots for loading completion and failure)

For more detailed information, you can read the official documents by yourself. I just selected some of them.

2.2 Using Suspense

1. In order to achieve asynchronous effects, we can use Promise to implement asynchronous operations.

2. We define the following component AsyncShow.vue component

<template>
	<!-- Wait 3 seconds to display data-->
    <h1>{{ result }}</h1>
</template>
<script lang="ts">
import { defineComponent } from 'vue';
export default defineComponent({
    setup() {
        return new Promise((resolve) => {
            setTimeout(() => {
                return resolve({
                    result: 43
                })
            }, 3000);
        });
    }
});
</script>
<style>
</style>

3. Use this component in App.vue

<script setup lang="ts">
import AsyncShow from './components/AsyncShow.vue';
</script>
<template>
  <img alt="Vue logo" src="./assets/logo.png" />
  <div class="test-useURLLoader">
    <!-- If the Promise is not completed, it will show Loding... After the Promise is completed, the value will be shown -->
    <Suspense>
      <template #default>
        <AsyncShow />
      </template>
      <template #fallback>
        <h2>
          Loading...
        </h2>
      </template>
    </Suspense>
  </div>
</template>
<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

2.3 Preview Effect

Please add a description of the image

Summarize

This article ends here. I hope it can be helpful to you. I also hope you can pay more attention to more content on 123WORDPRESS.COM!

You may also be interested in:
  • Two ways to dynamically create components in Vue
  • Summary of three ways to create Vue components
  • Detailed explanation of how to create and publish a vue component
  • How to create and pass values ​​in Vue components
  • An article to show you how to create and use Vue components

<<:  Pure CSS to achieve automatic rotation effect of carousel banner

>>:  A brief discussion on the correct approach to MySQL table space recovery

Recommend

Javascript to achieve the effect of closing advertisements

Here is a case study on how to close ads using Ja...

Introduction to installing and configuring JDK under CentOS system

Table of contents Preface Check and uninstall Ope...

Seven different color schemes for website design experience

The color matching in website construction is ver...

Detailed explanation of Nginx forwarding socket port configuration

Common scenarios for Nginx forwarding socket port...

MySQL's method of dealing with duplicate data (preventing and deleting)

Some MySQL tables may contain duplicate records. ...

Detailed explanation of nmcli usage in CentOS8

Common nmcli commands based on RHEL8/CentOS8 # Vi...

CentOS7 uses rpm to install MySQL 5.7 tutorial diagram

1. Download 4 rpm packages mysql-community-client...

Detailed explanation of the EXPLAIN command and its usage in MySQL

1. Scenario description: My colleague taught me h...

Detailed explanation of invisible indexes in MySQL 8.0

Word MySQL 8.0 has been released for four years s...

Detailed code for adding electron to the vue project

1. Add in package.json "main": "el...

Version numbers in css and js links in HTML (refresh cache)

background Search the keyword .htaccess cache in ...

JavaScript removes unnecessary properties of an object

Table of contents Example Method 1: delete Method...