Vue advanced usage tutorial dynamic components

Vue advanced usage tutorial dynamic components

I believe that dynamic components will be used most of the time in the development process. When we need to switch states between different components, dynamic components can meet our needs very well. The core of this is the use of the component tag and the is attribute.

Basic description

// vue
<div id="app">
  <button @click="changeTabs('child1')">child1</button>
  <button @click="changeTabs('child2')">child2</button>
  <button @click="changeTabs('child3')">child3</button>
  <component :is="chooseTabs">
  </component>
</div>
// js
var child1 = {
  template: '<div>content1</div>',
}
var child2 = {
  template: '<div>content2</div>'
}
var child3 = {
  template: '<div>content3</div>'
}
var vm = new Vue({
  el: '#app',
  components:
    child1,
    child2,
    child3
  },
  methods: {
    changeTabs(tab) {
      this.chooseTabs = tab;
    }
  }
})

AST parsing

The interpretation of <component> is consistent with the previous articles. It will start from the AST parsing stage. The process will not focus on every detail, but will specifically explain the differences from previous processing methods. The differences in dynamic component parsing are focused on processComponent. Due to the existence of the is attribute on the tag, it will mark the component attribute on the final ast tree.

// Analysis of dynamic components function processComponent (el) {
  var binding;
  // Get the value corresponding to the is attribute if ((binding = getBindingAttr(el, 'is'))) {
    // The ast tree has an additional component attribute el.component = binding;
  }
  if (getAndRemoveAttr(el, 'inline-template') != null) {
    el.inlineTemplate = true;
  }
}

Render Function

With the ast tree, the next step is to generate an executable render function based on the ast tree. Due to the component attribute, the generation process of the render function will go through the genComponent branch.

//render function generation function var code = generate(ast, options);

// implementation of generate function function generate (ast,options) {
  var state = new CodegenState(options);
  var code = ast ? genElement(ast, state) : '_c("div")';
  return {
    render: ("with(this){return " + code + "}"),
    staticRenderFns: state.staticRenderFns
  }
}

function genElement(el, state) {
  ···
  var code;
  // Dynamic component branch if (el.component) {
    code = genComponent(el.component, el, state);
  }
}

The processing logic for dynamic components is actually very simple. When there is no inline template flag (which will be discussed later), the subsequent child nodes are obtained for splicing. The only difference from ordinary components is that the first parameter of _c is no longer a specified string, but a variable representing the component.

// Processing function for dynamic components genComponent (
    componentName,
    el,
    state
  ) {
    // When the inlineTemplate attribute is set, children is null
    var children = el.inlineTemplate ? null : genChildren(el, state, true);
    
    return ("_c(" + componentName + "," + (genData$2(el, state)) + 
    (children ? ("," + children) : '') + ")")
  }

Comparison between normal components and dynamic components

Render function of ordinary components

"with(this){return _c('div',{attrs:{"id":"app"}},[_c('child1',[_v(_s(test))])],1)}"

Dynamic component render function

"with(this){return _c('div',{attrs:{"id":"app"}},[_c(chooseTabs,{tag:"component"})],1)}"

To summarize briefly, the difference between dynamic components and ordinary components is:

  1. The component attribute is added in the ast stage, which is a sign of dynamic components
  2. During the render function generation phase, due to the existence of the component attribute, the genComponent branch will be executed. genComponent will perform special processing on the execution function of dynamic components. Unlike ordinary components, the first parameter of _c is no longer an unchanging string, but a specified component name variable.
  3. The process from render to vnode is the same as that of ordinary components, except that the string is replaced with a variable and has a data attribute of { tag: 'component' }. In this example, chooseTabs takes child1.

Dynamic components in factory function form

You can also use dynamic components in the form of factory functions as follows:

const AsyncComponent = () => ({

  // Component to load (should be a `Promise` object)

  component: import('./MyComponent.vue'),

  //Component loading used when asynchronous component loading: LoadingComponent,

  // Component used when loading fails error: ErrorComponent,

  // Display the delay time of the component during loading. The default value is 200 (milliseconds)

  delay: 200,

  // If a timeout is provided and the component load times out,

  // Use the component used when loading fails. Default value is: `Infinity`

  timeout: 3000

});



components:

  AsyncComponent,

},

Summarize

This is the end of this article about advanced usage of Vue dynamic components. For more relevant Vue dynamic component content, please search 123WORDPRESS.COM’s previous articles 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 dynamic component instance analysis
  • Detailed explanation of Vue dynamic components and asynchronous components examples
  • Two ways to implement Vue dynamic subcomponents
  • Two ways to dynamically create components in Vue
  • Detailed explanation of Vue custom dynamic component example
  • Basic tutorial on using Vue dynamic components in front-end architecture

<<:  Solve the problem of managing containers with Docker Compose

>>:  HTML input box optimization to improve user experience and ease of use

Recommend

Zabbix monitors Linux hosts based on snmp

Preface: The Linux host is relatively easy to han...

Mac node deletion and reinstallation case study

Mac node delete and reinstall delete node -v sudo...

Introduction to HTML page source code layout_Powernode Java Academy

Introduction to HTML page source code layout This...

The easiest way to reset mysql root password

My mysql version is MYSQL V5.7.9, please use the ...

Vue3 AST parser-source code analysis

Table of contents 1. Generate AST abstract syntax...

15 JavaScript functions worth collecting

Table of contents 1. Reverse the numbers 2. Get t...

The button has a gray border that is ugly. How to remove it?

I used the dialog in closure and drew a dialog wit...

Vue routing to implement login interception

Table of contents 1. Overview 2. Routing Navigati...

Complete step record of vue encapsulation TabBar component

Table of contents Implementation ideas: Step 1: C...

Detailed code for adding electron to the vue project

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

Use PSSH to batch manage Linux servers

pssh is an open source software implemented in Py...

jQuery plugin to achieve code rain effect

This article shares the specific code of the jQue...

Implementation of docker-compose deployment of zk+kafka+storm cluster

Cluster Deployment Overview 172.22.12.20 172.22.1...