
This article explains how to reference HTML elements in components in Vue.js. You can switch views or component templates by using Vue Router or creating dynamic components.
Vue Router is used to navigate between views or component templates in the DOM. To use Vue Router, define a route in the route component and indicate to Vue that the new component should be mounted on an event (such as a click).
This is the correct way to handle navigation in sidebar and menu components within the user interface.
If you want to switch between two arbitrary components mounted in the DOM without creating a route, then you may want to use dynamic components.
Dynamic Components
Vue dynamic components allow users to switch between two or more components without routing, even after switching back Preserve data state when initializing components.
The core idea is to allow users to dynamically mount and uninstall components in the user interface without using a router.
Why are dynamic components important?
When designing a user interface, you need some form of flexibility to show or hide based on the application Nested components of program state. Dynamic components provide this platform in an efficient and simple way.
This feature saves you a lot of code because you can easily implement dynamic components using Vue conditional structures such as v-if and v-else. You can use conditional structures to implement dynamic components by using placeholders to easily bind logic to the component.
This approach ensures that your presentation is always clean and clear.
You can create dynamic components in Vue. On your computer, you will need the following information:
Node.js version 10.x and above installed. You can verify that you have Node.js version 10.x by running the following command in a terminal/command prompt:
node -v
A code editor (Visual Studio is recommended).
The latest version of Vue, installed globally on your computer.
Vue CLI 3.0 is installed on your computer. To do this, first uninstall the old CLI version:
npm uninstall -g vue-cli
Then, install a new one:
npm install -g @vue/cli
Syntax for dynamic components
Vue provides a special template element for dynamic components, referred to as component. The syntax is this:
<component v-bind:is=”currentComponent”></component>
The component element can also be a self-closing tag:
<component v-bind:is=”currentComponent”/>
The first option is best for browsing compatibility.
Demo
Download the starter project and open it in VS Code to get some examples of dynamic components. starter Projects allow you to access an existing test component, create a second test component, and switch between the two.
Navigate to the components folder and create a new file. Name the file Test2.vue and copy the following code block into the file:
<template>
<div><h1 id="I-nbsp-am-nbsp-Test-nbsp">I am Test 2</h1>
</div>
</template>
<script>
export default {
name: 'Test2',
props: {
msg: String
}
}
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
h3 {
margin: 40px 0 0;
}
ul {
list-style-type: none;
padding: 0;
}
li {
display: inline-block;
margin: 0 10px;
}
a {
color: #42b983;
}
</style> Now that you have your second component, go to App.vue File and register the component:
<template>
<div id="app">
<img src="/static/imghwm/default1.png" data-src="./assets/logo.png" class="lazy" alt="Vue logo" >
<Test />
<Test2 />
</div>
</template>
<script>
import Test from './components/Test.vue'
import Test2 from './components/Test2.vue'
export default {
name: 'app',
components: {
Test, Test2
}
}
</script>The two test components are now nested within the root application component. If you just want to mount one component and then dynamically switch to another component, you have to create a dynamic component.
Copy the following code block into the template section of the app.vue file:
<template>
<div id="app">
<img src="/static/imghwm/default1.png" data-src="./assets/logo.png" class="lazy" alt="Vue logo" >
<component is="Test" />
</div>
</template>Next, run the application using the following serve command :
npm run serve
You will see that only the Test 1 component is displayed.
This is exactly the response you would get if only the Test 1 element was specified in the template. To make a component dynamic, we can bind it to the set property using the v-bind directive.
<template>
<div id="app">
<img src="/static/imghwm/default1.png" data-src="./assets/logo.png" class="lazy" alt="Vue logo" >
<component v-bind:is="component" />
</div>
</template>
<script>
import Test from './components/Test.vue'
import Test2 from './components/Test2.vue'
export default {
name: 'app',
components: {
Test, Test2
},
data (){
return {
component:"Test"
}
}
}
</script>Your component is now bound to the component property in the data. If you switch the component to Test2, it will automatically mount the Test2 component.
Test it on the browser.
Add method calls
You can add method calls to control the logic of dynamic display of components. The component element allows you to access every construct in your Vue instance.
The following is an example of a small method to switch these two components:
<template>
<div id="app">
<img src="/static/imghwm/default1.png" data-src="./assets/logo.png" class="lazy" alt="Vue logo" >
<component v-bind:is="component" />
<button v-on:click="toggle">Toggle</button>
</div>
</template>
<script>
import Test from './components/Test.vue'
import Test2 from './components/Test2.vue'
export default {
name: 'app',
components: {
Test,
Test2
},
data (){
return {
component:"Test2"
}
},
methods: {
toggle(){
if (this.component === Test) {
this.component = Test2;
} else {
this.component = Test;
}
}
}
}
</script>Keep the data value valid when switching
When the Vue team built this feature, they chose to extend its functionality to include storing data values for each state.
In order to store this data, Vue provides a template element named keep-alive. Using keep-alive, you can ensure that your component state remains intact after switching back from one component to another.
For example, if you click a link or enter a value in a text box and then switch the component, keep-alive will take you back to the same location you were using when you switched back Link or text box.
To enable keep-alive, go to the templates section of the app.vue file and wrap the component element with a keep-alive element :
<keep-alive> <component v-bind:is="component" /> </keep-alive>
要查看它是否工作,请将表单元素添加到测试中。vue文件,在模板部分添加如下代码块:
<template>
<div><h1 id="I-nbsp-am-nbsp-Test-nbsp">I am Test 1</h1>
<form>
First name:<br>
<input type="text" name="firstname"><br>
Last name:<br>
<input type="text" name="lastname">
</form>
</div>
</template>保存所有项目文件后,再次运行应用程序。在输入框中键入,切换组件,并切换回原始组件。您将注意到在切换组件之前输入的值与之前输入的值完全相同。

结论
本文介绍了如何在Vue.js工作流中使用动态组件。您现在还可以通过keep-alive扩展组件元素的能力。
相关推荐:
更多编程相关知识,请访问:编程入门!!
The above is the detailed content of How to use dynamic components in Vue.js. For more information, please follow other related articles on the PHP Chinese website!
Netflix's Frontend: Examples and Applications of React (or Vue)Apr 16, 2025 am 12:08 AMNetflix uses React as its front-end framework. 1) React's componentized development model and strong ecosystem are the main reasons why Netflix chose it. 2) Through componentization, Netflix splits complex interfaces into manageable chunks such as video players, recommendation lists and user comments. 3) React's virtual DOM and component life cycle optimizes rendering efficiency and user interaction management.
The Frontend Landscape: How Netflix Approached its ChoicesApr 15, 2025 am 12:13 AMNetflix's choice in front-end technology mainly focuses on three aspects: performance optimization, scalability and user experience. 1. Performance optimization: Netflix chose React as the main framework and developed tools such as SpeedCurve and Boomerang to monitor and optimize the user experience. 2. Scalability: They adopt a micro front-end architecture, splitting applications into independent modules, improving development efficiency and system scalability. 3. User experience: Netflix uses the Material-UI component library to continuously optimize the interface through A/B testing and user feedback to ensure consistency and aesthetics.
React vs. Vue: Which Framework Does Netflix Use?Apr 14, 2025 am 12:19 AMNetflixusesacustomframeworkcalled"Gibbon"builtonReact,notReactorVuedirectly.1)TeamExperience:Choosebasedonfamiliarity.2)ProjectComplexity:Vueforsimplerprojects,Reactforcomplexones.3)CustomizationNeeds:Reactoffersmoreflexibility.4)Ecosystema
The Choice of Frameworks: What Drives Netflix's Decisions?Apr 13, 2025 am 12:05 AMNetflix mainly considers performance, scalability, development efficiency, ecosystem, technical debt and maintenance costs in framework selection. 1. Performance and scalability: Java and SpringBoot are selected to efficiently process massive data and high concurrent requests. 2. Development efficiency and ecosystem: Use React to improve front-end development efficiency and utilize its rich ecosystem. 3. Technical debt and maintenance costs: Choose Node.js to build microservices to reduce maintenance costs and technical debt.
React, Vue, and the Future of Netflix's FrontendApr 12, 2025 am 12:12 AMNetflix mainly uses React as the front-end framework, supplemented by Vue for specific functions. 1) React's componentization and virtual DOM improve the performance and development efficiency of Netflix applications. 2) Vue is used in Netflix's internal tools and small projects, and its flexibility and ease of use are key.
Vue.js in the Frontend: Real-World Applications and ExamplesApr 11, 2025 am 12:12 AMVue.js is a progressive JavaScript framework suitable for building complex user interfaces. 1) Its core concepts include responsive data, componentization and virtual DOM. 2) In practical applications, it can be demonstrated by building Todo applications and integrating VueRouter. 3) When debugging, it is recommended to use VueDevtools and console.log. 4) Performance optimization can be achieved through v-if/v-show, list rendering optimization, asynchronous loading of components, etc.
Vue.js and React: Understanding the Key DifferencesApr 10, 2025 am 09:26 AMVue.js is suitable for small to medium-sized projects, while React is more suitable for large and complex applications. 1. Vue.js' responsive system automatically updates the DOM through dependency tracking, making it easy to manage data changes. 2.React adopts a one-way data flow, and data flows from the parent component to the child component, providing a clear data flow and an easy-to-debug structure.
Vue.js vs. React: Project-Specific ConsiderationsApr 09, 2025 am 12:01 AMVue.js is suitable for small and medium-sized projects and fast iterations, while React is suitable for large and complex applications. 1) Vue.js is easy to use and is suitable for situations where the team is insufficient or the project scale is small. 2) React has a richer ecosystem and is suitable for projects with high performance and complex functional needs.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 Linux new version
SublimeText3 Linux latest version

Dreamweaver CS6
Visual web development tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.







