Home >Web Front-end >Vue.js >How to use dynamic components in Vue.js

How to use dynamic components in Vue.js

青灯夜游
青灯夜游forward
2020-09-28 17:28:494269browse

How to use dynamic components in Vue.js

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>I am Test 2</h1>
  </div>
</template>
<script>
export default {
  name: &#39;Test2&#39;,
  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 alt="Vue logo" src="./assets/logo.png">
    <Test />
    <Test2 />
  </div>
</template>
<script>
import Test from &#39;./components/Test.vue&#39;
import Test2 from &#39;./components/Test2.vue&#39;
export default {
  name: &#39;app&#39;,
  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 alt="Vue logo" src="./assets/logo.png">
    <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 alt="Vue logo" src="./assets/logo.png">
    <component v-bind:is="component" />
  </div>
</template>
<script>
import Test from &#39;./components/Test.vue&#39;
import Test2 from &#39;./components/Test2.vue&#39;
export default {
  name: &#39;app&#39;,
  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 alt="Vue logo" src="./assets/logo.png">
    <component v-bind:is="component" />
    <button v-on:click="toggle">Toggle</button>
  </div>
</template>
<script>
import Test from &#39;./components/Test.vue&#39;
import Test2 from &#39;./components/Test2.vue&#39;
export default {
  name: &#39;app&#39;,
  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>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>

保存所有项目文件后,再次运行应用程序。在输入框中键入,切换组件,并切换回原始组件。您将注意到在切换组件之前输入的值与之前输入的值完全相同。

How to use dynamic components in Vue.js

结论

本文介绍了如何在Vue.js工作流中使用动态组件。您现在还可以通过keep-alive扩展组件元素的能力。

相关推荐:

2020年前端vue面试题大汇总(附答案)

vue教程推荐:2020最新的5个vue.js视频教程精选

更多编程相关知识,请访问:编程入门!!

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!

Statement:
This article is reproduced at:logrocket.com. If there is any infringement, please contact admin@php.cn delete