vue文件中的name

官方文档指出:name只有作为组件选项时起作用,简单的可以理解为name属性和组件相关,当需要处理组件方面的问题才会用到name属性。
常见的几种用法:
1.递归组件
vue中允许组件模板调用自身,这时候我们就可以使用到name属性,当我们设置了组件的name,组件递归调用自身使用的组件名就是name

//递归子组件 child.vue
<template>
  <div class="child">
    <!-- 递归组件 -->
    <div v-for="(item, index) in treeData" :key="index">
      <p>{{ item.title }}</p>
      <div class="children" v-if="item.children">
        <!-- 嵌套自身 -->
        <childTree :treeData="item.children"></childTree>
      </div>
    </div>
  </div>
</template>
<script>
export default {
  name: "childTree",
  props: ["treeData"],
  data() {
    return {};
  },
  mounted() {},
};
</script>
<style lang="stylus" scoped>
.children {
  padding-left: 10px;
}
</style>

在父组件中只需要定义数据结构,传给递归子组件

<template>
  <div class="father">
    <!-- 父组件调用递归组件child.vue -->
    <Child :treeData="treeData"></Child>
  </div>
</template>
<script>
import Child from "./child.vue";
export default {
  name: "",
  components: {
    //注册组件
    Child,
  },

  data() {
    return {
      treeData: [
        {
          title: "递归层1",
          children: [
            {
              title: "递归层1-1",
              children: [
                {
                  title: "递归层1-1-1",
                },
                {
                  title: "递归层1-1-2",
                },
              ],
            },
          ],
        },
        {
          title: "递归层2",
          children: [
            {
              title: "递归层2-1",
              children: [
                {
                  title: "递归层2-1-1",
                },
              ],
            }
          ],
        },
      ],
    };
  },
};
</script>

效果图:
image.png

2.配合keep-alive对组件缓存做限制(include/exclude="name")
keep-alive的 include和exclude 允许有条件的对组件进行缓存,其中include和exclude所匹配的就是组件的name值

<!-- 把除了组件名是 todolist,home 的组件缓存起来 -->
<keep-alive exclude="todolist,home">
  <router-view></router-view>
</keep-alive>

3.在dev-tools中使用
在开发中我们经常需要对代码进行调试,在dev-tools中组件是以组件name进行显示的,这样更有语义化,方便我们快速定位到我们需要审查的位置,结构更清晰明了。

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容