动态组件

367 阅读1分钟

动态组件的功能

页面中的某个地方需要在不同组件之间进行动态切换,这时候除了条件渲染,还可以使用动态组件。

动态组件的语法

1.利用 元素的 is 属性语法

2.is 属性应该用 v-bind 修饰(可以简写为 : )

3.is属性应该传入注册过的组件名,且is属性应该传入一个字符串

component 标签的is后跟组件的变量名决定使用哪个组件来渲染

<component  is="Sinabox"></component>==><Sinabox/>

<component v-bind:is="mycomponent"></component>
ps: is是组件名  :is是data中的变量中保存的组件名,保存组件名时需要用字符串保存。

当is属性传入一个没有注册过的组件名,会被当作自定义标签名vue会发出警告然后文档树中会添加一个自定义标签,而当传入的是原生的标签名,同样也会创建一个该标签。

使用案例

<template>
  <div id="app">
    <h1>黑暗森林</h1>
    <button @click="componentId = 'Two'">two组件</button>
    <button @click="componentId = 'three'">three组件</button>
    <component :is="componentId"></component>
  </div>
</template>

<script>
import Two from "@/components/Two.vue";
import three from "@/components/three.vue";
export default {
  data() {
    return {
      componentId: "Two",
    };
  },
  components: {
    Two,
    three,
  },
};
</script>

<style lang="scss">
#app {
  width: 700px;
  height: 400px;
  background-color: goldenrod;
}
</style>

2.gif