谈Vue组件的is特性

时间:2022-07-25
本文章向大家介绍谈Vue组件的is特性,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

前言

大家好,我是你们的小编,今天我们的话题是谈Vue组件的is特性,组件是Vue的中强大的功能之一,组件可以扩展HTMl,进行封装提高复用性,增加了开发效率,因此,Vue为此添加了特殊的功能is,那么is的特性在哪里呢有什么用途呢?

限制元素

其实简单的说,vue模板也是dom模板,在浏览器解析的过程中,也是通过原生浏览器解析dom,那么这样由于对dom的限制进而对vue模板也产生了限制,导致vue的组件中有一些标签是不能放置的,比如ul,select,a,table,dl等等这些标签中,所以需要增添is特性来扩展,从而达到可以在这些受限制的html中使用:

<ul>
   <li is="my-component"></li>
</ul>

而不能使用下面这样形式的写法,导致Vue将自定义组件视为无效内容,渲染出错:

<ul>
   <my-component></my-component>
</ul>

温馨提示

如果使用下面模板的话,这个限制是不存在的

字符串 (例如:template: '...')
单文件组件 (.vue)
<script type="text/x-template">

动态组件

在我们平时使用vue中的模板的时候,许多时候都是直接定义成一个固定的模板,但是,vue中提供了一个动态模板,可以在任意模板中切换,就是用vue中<component>用:is来挂载不同的组件。

<template>
  <ul>
    <button @click="components = 'myComponent'">my</button>
    <button @click="components = 'youComponent'">you</button>
    <button @click="components = 'otherComponent'">other</button>
    <component :is="components"></component>
  </ul>
</template>
<script>
import myComponent from "./components/mycomponent";
import youComponent from "./components/youcomponent";
import otherComponent from "./components/othercomponent";
export default {
  data() {
    return {
      components: "myComponent"
    };
  },
  components: {
    myComponent,
    youComponent,
    otherComponent
  }
};
</script>

我们在components中注册了三个模板,当我们点击当前按钮的时候,就会将模板切换模板,可以说是非常方便了。