Use Vue3 to implement a component that can be called with js

Use Vue3 to implement a component that can be called with js

Preface

Component libraries are basically used in project development, but the style and functions of the design draft may not be the same as those of the component library, especially for message prompt pop-ups and confirmation pop-ups. Each project and each designer has his own style. Although we can use the components in the component library to override its style. However, some customized functions are still not easy to modify. In this case, we will choose custom components, and then introduce them into the page through the components attribute, and explicitly write tag calls. For message prompts that give users simple prompts or operations, most commonly used UI libraries support similar functions through js calls. We can also refer to the calling method of the UI library to implement a custom component called by a js function.

1. Conventional Vue components

Suppose we need to implement a confirmation box, click a button to open the confirmation box, click the OK and Cancel buttons of the confirmation box to close the confirmation box, and call the corresponding method.

1. Main component code:

src/components/Confirm/Confirm.vue

2. Usage

3. Achieve results

2. Change to js call component

The above method of calling components is very cumbersome. It requires both introduction and processing of callbacks of various operations. In addition, the component DOM node is inserted under the current page, and the style may be overwritten by the component content or affected by other factors.

The result we want to achieve is: calling the component through a js function, the function returns a promise, confirms then, and cancels catch`, for example:

Confirm({
  title: '',
  message: ''
}).then(() => {
  // Click to confirm}).catch(() => {
  // Click to cancel })

1. Implementation steps:

  • First, confirm that a promise object needs to be returned. Create a method that first returns a promise object.
  • Use Vue's createApp method to create a Confirm component instance. Using the second argument to createApp, we can pass the root prop to the application, passing in the data that the component needs.
  • Create a node to be used as a container for mounting component instances, and append the node to the body.
  • By mounting the component instance to the created node, the parent of the component is the body and will not be affected by the calling page.
  • When you click OK, resolve is called, the current component is uninstalled, and the DOM is removed. Click Cancel to call reject and uninstall the current component, removing the DOM.

2. Specific implementation code:

Modify the Confirm component js part and pass onConfirm and onCancel from props to facilitate the use of component instances.

// src/components/Confirm/Confirm.vue
<script>
export default {
  name: 'Confirm',
  props: {
    title:
      type: String,
      default: 'prompt'
    },
    message: {
      type: String,
      default: 'Default prompt message'
    },
    confirmBtnText: {
      type: String,
      Default: 'Confirm'
    },
    cancelBtnText: {
      type: String,
      default: 'Cancel'
    },
    onConfirm: {
      type: Function,
      default: () => {}
    },
    onCancel: {
      type: Function,
      default: () => {}
    }
  }
}
</script>

Create a new index.js file in the same directory, pass parameters such as onConfirm and onCancel to the component through props, and you can receive event callbacks in the instance.

// src/components/Confirm/index.js
import { createApp } from 'vue'
import Confirm from './Confirm'
function confirm ({ title, message, confirmBtnText, cancelBtnText }) {
  return new Promise((resolve, reject) => {
    // Instantiate the component, the second parameter of createApp is props
    const confirmInstance = createApp(Confirm, {
      title: title || 'Tips',
      message: message || 'Confirm message',
      confirmBtnText: confirmBtnText || 'Confirm',
      cancelBtnText: cancelBtnText || 'Cancel',
      onConfirm: () => {
        unmount()
        resolve()
      },
      onCancel: () => {
        unmount()
        reject(new Error())
      }
    })
    // Unmount component const unmount = () => {
      confirmInstance.unmount()
      document.body.removeChild(parentNode)
    }
    // Create a mounting container const parentNode = document.createElement('div')
    document.body.appendChild(parentNode)
    //Mount component confirmInstance.mount(parentNode)
  })
}

export default confirm

Using Components

setup () {
  const showConfirm = () => {
    Confirm({
      title: 'Title',
      message: 'Content'
    }).then(() => {
      console.log('Click to confirm')
    }).catch(() => {
      console.log('Click to cancel')
    })
  }
  return {
    showConfirm
  }
}

3. Realize the effect display

Summarize

This is the end of this article about using Vue3 to implement a component that can be called by js. For more relevant content about Vue3 implementing components called by js, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Vue parent-child component mutual value transfer and call
  • Vue encapsulates multiple components to call the same interface
  • How to call child component functions in vue parent component
  • Detailed explanation of the use of Vue component slots and calling methods within components
  • Vue child component communicates with parent component and parent component calls method in child component
  • Detailed explanation of the case of Vue child component calling parent component method

<<:  Linux user and group command example analysis [switching, adding users, permission control, etc.]

>>:  Discussion on more reasonable creation rules for MySQL string indexes

Recommend

How to set password for mysql version 5.6 on mac

MySQL can be set when it is installed, but it see...

CSS uses the autoflow attribute to achieve seat selection effect

1. Autoflow attribute, if the length and width of...

Modularity in Node.js, npm package manager explained

Table of contents The basic concept of modularity...

Tutorial on installing Apache 2.4.41 on Windows 10

1. Apache 2.4.41 installation and configuration T...

Detailed tutorial on installing MySQL 5.7.20 on RedHat 6.5/CentOS 6.5

Download the rpm installation package MySQL offic...

CSS pseudo-element::marker detailed explanation

This article will introduce an interesting pseudo...

Detailed explanation of the use of filter properties in CSS3

Recently, when I was modifying the intranet porta...

Gitlab practical tutorial uses git config for related configuration operations

This article introduces the content related to gi...

How to install Solr 8.6.2 in Docker and configure the Chinese word segmenter

1. Environment version Docker version 19.03.12 ce...

Introduction to the use of html base tag target=_parent

The <base> tag specifies the default address...

Design Theory: Text Legibility and Readability

<br />Not long ago, due to business needs, I...

Installation and configuration tutorial of MySQL 8.0.16 under Win10

1. Unzip MySQL 8.0.16 The dada folder and my.ini ...

Detailed explanation of basic concepts of HTML

What is HTML? HTML is a language used to describe...

Instructions for using the --rm option of docker run

When the Docker container exits, the file system ...