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

Pure CSS to achieve a single div regular polygon transformation

In the previous article, we introduced how to use...

Summary of Vue watch monitoring methods

Table of contents 1. The role of watch in vue is ...

Stealing data using CSS in Firefox

0x00 Introduction A few months ago, I found a vul...

Graphic tutorial on installing tomcat8 on centos7.X Linux system

1. Create the tomcat installation path mkdir /usr...

18 Web Usability Principles You Need to Know

You can have the best visual design skills in the...

Two ways to build a private GitLab using Docker

The first method: docker installation 1. Pull the...

Detailed example of jQuery's chain programming style

The implementation principle of chain programming...

Detailed explanation of client configuration for vue3+electron12+dll development

Table of contents Modify the repository source st...

Web front-end development CSS related team collaboration

The front-end development department is growing, ...

How to configure Openbox for Linux desktop (recommended)

This article is part of a special series on the 2...

HTML+CSS makes div tag add delete icon in the upper right corner sample code

1. Requirements description Display the delete ic...