Element-UI源码——Link文字链接

214 阅读1分钟

Link文字链接

对a标签的封装

 <template>
   <!-- class样式列表 包括类型 是否禁用 和下划线
   href链接
   绑定$attrs中的属性
    -->
   <a
     :class="[
       'el-link',
       type ? `el-link--${type}` : '',
       disabled && 'is-disabled',
       underline && !disabled && 'is-underline',
     ]"
     :href="disabled ? null : href"
     v-bind="$attrs"
     @click="handleClick"
   >
   <!-- 图标 -->
     <i :class="icon" v-if="icon"></i>
   <!-- 插槽 -->
     <span v-if="$slots.default" class="el-link--inner">
       <slot></slot>
     </span>
     <!-- 也可以这么使用<el-link >默认链接
     <template v-slot:icon>
       <i class="el-icon-eleme"></i>
     </template>
   </el-link> -->
   <!-- 具名插槽 -->
     <template v-if="$slots.icon"
       ><slot v-if="$slots.icon" name="icon"></slot
     ></template>
   </a>
 </template>
 ​
 <script>
 export default {
   name: "ElLink",
 ​
   props: {
     // 类型
     type: {
       type: String,
       default: "default",
     },
     // 是否下划线
     underline: {
       type: Boolean,
       default: true,
     },
     // 是否禁用状态
     disabled: Boolean,
     // 原生 href 属性
     href: String,
     // 图标类名
     icon: String,
   },
 ​
   methods: {
     // 点击事件 当没有被禁用 没有href属性时可以调用组件上定义的click
     handleClick(event) {
       if (!this.disabled) {
         if (!this.href) {
           this.$emit("click", event);
         }
       }
     },
   },
 };
 </script>
 ​

其中v-bind="$attrs"的作用是将调用组件时的组件标签上绑定的非props的特性(class和style除外)向下传递,也就是说当没有使用props接收时可以获取到

MyGrandFather.vue

 <template>
   <MyFather name='2' age="1" gender="3"></MyFather>
 </template>
 ​
 <script>
 import MyFather from '@/view/MyFather'
 export default {
     components:{MyFather}
 }
 </script>

MyFather.vue

 
 <template>
   <MySon v-bind="$attrs"></MySon>
 </template>
 <script>
 import MySon from './MySon.vue';
 export default {
   //inheritAttrs:false,
     components:{
       MySon
     }
 }
 </script>

MySon.vue

 <template>
     <div>
       <div>1</div>
     </div>
 </template>
 <script>
 export default {
   //inheritAttrs:false,
   props:['age'],
   mounted(){
       console.log(this.$attrs);
     //{gender:'3',name:'2'}
   }
 }
 </script>

vm.$attrs的作用

包含了父作用域中不作为 prop 被识别 (且获取) 的 attribute 绑定 (classstyle 除外)。当一个组件没有声明任何 prop 时,这里会包含所有父作用域的绑定 (classstyle 除外),并且可以通过 v-bind="$attrs" 传入内部组件——在创建高级别的组件时非常有用。

此时的页面为

image-20240401012809124.png

可以看到html标签上加上了属性,如果想去掉,加入inheritAttrs:false,

image-20240401012850635.png

inheritAttrs的作用

默认情况下,父组件传递的,但没有被子组件解析为 props 的 attributes 绑定会被“透传”。这意味着当我们有一个单根节点的子组件时,这些绑定会被作为一个常规的 HTML attribute 应用在子组件的根节点元素上。当你编写的组件想要在一个目标元素或其他组件外面包一层时,可能并不期望这样的行为。我们可以通过设置 inheritAttrsfalse 来禁用这个默认行为。这些 attributes 可以通过 $attrs 这个实例属性来访问,并且可以通过 v-bind 来显式绑定在一个非根节点的元素上。