This is the 21st day of my participation in Gwen Challenge

preface

Familiar with object-oriented brothers must know how to use polymorphism to achieve different state management and method application

In Vue, components are an important part of our development process

In particular business requirements, there may be situations where different components need to be presented based on different types

The use of v-If is considered inelegant by the author

At this point, the concept of dynamic components caught my attention

Dynamic components

introduce

The official Vue documentation has a brief explanation of dynamic components

But the content is too substantial to be easily understood

Therefore, the author simply summarizes the dynamic components:

  1. Use the Component tag
  2. Render according to binding properties
  3. Support for parameter passing

So, to use dynamic components, the requirements we face are as follows:

  1. The data received and the events passed are essentially the same
  2. Internal business logic is hidden from the current page

Do you realize that this is actually a lot like an interface and its bunch of implementation classes?

implement

Assume the following scenario: an item in a form is uncertain. It could be an input box or a number box, but the style Settings are basically the same

UI we use Ant Design Vue, which implements these two components:

<a-input id="test" style="width: 20%" />
<a-input-number id="test" style="width: 20%" />
Copy the code

The traditional way of writing:

<a-input v-if="type === 'input'" id="test" placeholder="Dynamic input box" style="width: 20%" />
<a-input-number v-else id="test" placeholder="Dynamic input box" style="width: 20%" />
Copy the code

Use dynamic routing to replace, the whole code:

<template>
  <div class="test">
    <component :is="type" v-bind="options"></component>
    <button @click="change">Switch type</button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      types: ["a-input"."a-input-number"].type: "a-input".options: {
        id: "test".placeholder: "Dynamic input box".style: "width: 20%",}}; },methods: {
    change() {
      this.type = this.types[this.types.indexOf(this.type) ^ 1]; }}};</script>

<style></style>
Copy the code

The is attribute corresponds to the component name. The input box is A-input, and the number box is A-input-number

Components change by toggling the value of the IS property

conclusion

Personally, I think dynamic components are widely used, such as dynamic forms, form customization and so on

I hope the simple article can provide some help to the brothers who have no idea