Vue3 new API usage

Author: Gorit

Date: December 5, 2021

Website: CodingGorit station

Blog post published in 2021: 25 / 30

We use vite to build a Vue3 + TS project. I will use < script setup lnag = "ts" > and < script lang = "ts" > mixed programming to implement it

1, Teleport

Official document of Teleport

1.1 introduction to teleport

  1. Vue encourages us to build our UI by encapsulating the UI and related behaviors into components. We can nest them together to build the tree that makes up the application UI.
  2. However, sometimes a part of a component template logically belongs to that component, and from a technical point of view, it is best to move this part of the template to another location in the DOM, that is, outside the Vue application.

Does the above words look silly, but they are actually translated from official documents

In fact, I understand that teleport is to mount a component outside Vue app. As we know, Vue belongs to SPA (single page) application. All renderings are in the tag with id app. In this way, we can create a component at the same level as app and reference it through the report tag, which can be used on any page

1.2 using Teleport

  1. We also implement a global modal box here
  2. Through the parent-child component communication mechanism, the mount feature of teleport is used
<!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 and app Peer label modal -->
    <script type="module" src="/src/main.ts"></script>
  </body>
</html>

  1. Define a Modal component
<template>
	<!-- teleport There's one to Property, mounted in id by modal On the label -->
    <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 inserts -->
                <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
    },
    // verification
    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>
  1. Using Modal components
<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 modal
    </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

2, Suspend

Suspend official documents

Waring: as an experimental function in Vue3, it can be modified at any time, so it is not recommended to use it for generating environment applications

2.1 introduction

  1. Suspend can be used for asynchronous data. It has a local processing method to adapt to a variety of situations
  2. One out of two (loaded and failed slots) is provided

For more detailed content, you can read the official documents by yourself. I'm just making a partial selection

2.2 use suspend

  1. In order to achieve asynchronous effect, we can use Promise to realize asynchronous operation.

  2. We define the following components: AsyncShow.vue component

<template>
	<!-- Wait 3 seconds to display the 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>
  1. 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">
    <!-- Promise When the execution is not completed, the Loding... After execution, the value will be displayed -->
    <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

Tags: Javascript Front-end Vue.js

Posted on Sun, 05 Dec 2021 06:31:54 -0500 by bhawap