In-depth understanding of Vue dynamic components and asynchronous components

In-depth understanding of Vue dynamic components and asynchronous components

1. Dynamic Components

<!DOCTYPE html>
<html>
<head>
 <meta charset="utf-8">
 <style>
		#app {
			font-size: 0
		}
		.dynamic-component-demo-tab-button {
			padding: 6px 10px;
			border-top-left-radius: 3px;
			border-top-right-radius: 3px;
			border: 1px solid #ccc;
			cursor: pointer;
			margin-bottom: -1px;
			margin-right: -1px;
			background: #f0f0f0;
		}
		.dynamic-component-demo-tab-button.dynamic-component-demo-active {
			background: #e0e0e0;
		}
		.dynamic-component-demo-tab-button:hover {
			background: #e0e0e0;
		}
		.dynamic-component-demo-posts-tab {
			display: flex;					
		}
		.dynamic-component-demo-tab {
			font-size: 1rem;
			border: 1px solid #ccc;
			padding: 10px;
		}
		.dynamic-component-demo-posts-sidebar {
			max-width: 40vw;
			margin: 0 !important;
			padding: 0 10px 0 0 !important;
			list-style-type: none;
			border-right: 1px solid #ccc;
			line-height: 1.6em;
		}
		.dynamic-component-demo-posts-sidebar li {
			white-space: nowrap;
			text-overflow: ellipsis;
			overflow: hidden;
			cursor: pointer;
		}
		.dynamic-component-demo-active {
			background: lightblue;
		}
		.dynamic-component-demo-post-container {
			padding-left: 10px;
		}
		.dynamic-component-demo-post > :first-child {
			margin-top: 0 !important;
			padding-top: 0 !important;
		}
 </style>
 <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>
<body>
<div id="app">
	<button v-for="tab in tabs" class="dynamic-component-demo-tab-button" 
		v-bind:class="{'dynamic-component-demo-active': tab === currentTab}" 
		@click="currentTab = tab">{{ tab }}</button>	
	<keep-alive>
		<component v-bind:is="currentTabComponent"></component>
	</keep-alive>
</div>
<script>
 Vue.component('tab-posts', {
		data: function(){
			return {
				posts:
					{id: 1, title: 'Cat Ipsum', content: 'Cont wait for the storm to pass, ...'},
					{id: 2, title: 'Hipster Ipsum', content: 'Bushwick blue bottle scenester ...'},
					{id: 3, title: 'Cupcake Ipsum', content: 'Icing dessert souffle ...'},
				],
				selectedPost: null
			}
		},
 template: `<div class="dynamic-component-demo-posts-tab dynamic-component-demo-tab">
						<ul class="dynamic-component-demo-posts-sidebar">
							<li v-for="post in posts" 
								v-bind:key="post.id" 
								v-on:click="selectedPost = post" 
								v-bind:class="{'dynamic-component-demo-active': post===selectedPost}">
								{{ post.title }}
							</li>
						</ul>
						<div class="dynamic-component-demo-post-container">
							<div v-if="selectedPost" class="dynamic-component-demo-post">
								<h3>{{ selectedPost.title }}</h3>
								<div v-html="selectedPost.content"></div>
							</div>
							<strong v-else>
								Click on a blog title to the left to view it.
							</strong>
						</div>
					</div>`
 });
	
	Vue.component('tab-archive', {
		template: '<div class="dynamic-component-demo-tab">Archive component</div>'
	});

 new Vue({
 el: '#app',
		data: {
			currentTab: 'Posts',
			tabs: ['Posts', 'Archive']
		},
		computed: {
			currentTabComponent: function(){
				return 'tab-' + this.currentTab.toLowerCase()
			}
		}
 });
</script>
</body>
</html> 

Using keep-alive on dynamic components can maintain the state of the component when the component is switched, avoiding performance issues caused by repeated rendering.

2. Asynchronous components

Vue allows you to define your components as a factory function, which will asynchronously resolve your component definition.

Vue.component('async-example', function (resolve, reject) {})

Here you can review Vue.js — Component Basics.

We use a Vue project bundled with webpack to introduce asynchronous components.

<!-- HelloWorld.vue -->
<template>
 <div>
 <h2 class="title">{{msg}}</h2>
 </div>
</template>

<script>
export default {
 data () {
 return {
 msg: 'Hello Vue!'
 }
 }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
 .title {
 padding: 5px;
 color: white;
 background: gray;
 }
</style>
<!-- App.vue -->
<template>
 <div id="app">
 <HelloWorld/>
 </div>
</template>

<script>
import HelloWorld from './components/HelloWorld'

export default {
 name: 'App',
 components:
 HelloWorld
 }
}
</script>

<style>
</style>

We change the content of the <script> tag of App.vue to:

export default {
 name: 'App',
 components:
 HelloWorld: () => import('./components/HelloWorld')
 }
}

This implements the function of the App component asynchronously loading the HelloWorld component.

We can achieve on-demand loading.

<!-- App.vue -->
<template>
 <div id="app">
 <button @click="show = true">Load Tooltip</button>
 <div v-if="show">
 <HelloWorld/>
 </div>
 </div>
</template>

<script>
export default {
 data: () => ({
 show:false
 }),
 components:
 HelloWorld: () => import('./components/HelloWorld')
 }
}
</script>

<style>
</style>

The asynchronous component factory function here can also return an object in the following format:

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
})

refer to:

Dynamic Components & Async Components — Vue.js

The above is the detailed content of in-depth understanding of Vue dynamic components and asynchronous components. For more information about Vue dynamic components and asynchronous components, please pay attention to other related articles on 123WORDPRESS.COM!

You may also be interested in:
  • How to use Vue3 asynchronous data loading component suspense
  • Vue3.0+vite2 implements dynamic asynchronous component lazy loading
  • Vue implements on-demand component loading and asynchronous component functions
  • Detailed explanation of Vue dynamic components and asynchronous components
  • Detailed explanation of asynchronous components in Vue component development

<<:  Solution to the problem of slow docker pull image speed

>>:  The correct way to migrate MySQL data to Oracle

Recommend

Detailed explanation of how to use Docker-Compose commands

You can manage and deploy Docker containers in a ...

How to run the react project on WeChat official account

Table of contents 1. Use the a tag to preview or ...

In-depth understanding of Vue's method of generating QR codes using vue-qr

Table of contents npm download step (1) Import (2...

Add a floating prompt for the header icon in the ElementUI table

This article mainly introduces how to add floatin...

An article teaches you how to use js to achieve the barrage effect

Table of contents Create a new html file: Create ...

Detailed explanation of JavaScript to monitor route changes

Table of contents history pushState() Method push...

Detailed explanation of Angular parent-child component communication

Table of contents Overview 1. Overview of input a...

How to turn local variables into global variables in JavaScript

First we need to know the self-calling of the fun...

JavaScript to achieve the effect of clicking on the submenu

This article shares the specific code of JavaScri...

OpenSSL implements two-way authentication tutorial (with server and client code)

1. Background 1.1 Problems A recent product testi...

How to expand the disk space of Linux server

Table of contents Preface step Preface Today I fo...

JavaScript to implement simple carousel chart most complete code analysis (ES5)

This article shares the specific code for JavaScr...