Vue encapsulates an IconFONT component

  • Let me show you my iconfont project

  • Create an Icon file with the following code
<template>
  <i class="iconfont" :class="type"></i>
</template>

<script>
export default {
  props: {type: {type:String.require:true}}}</script>

<style scoped>
@import '//at.alicdn.com/t/font_2648132_8d1o1q9779s.css'; // To import CSS generated for the selected iconfont, see the project for the specific address.iconfont {
  color: inherit;
  font-size: inherit;
}
</style>
Copy the code
  • The parent component code is as follows
<template>
  <div id="app">
    <Icon type="icon-guandao" />
  </div>
</template>

<script>
import Icon from './components/Icon'
export default {
  name: 'App'.components: {
    Icon
  }
}
</script>

<style scoped>
.iconfont{
  color: red;
  font-size: 30px;
}
</style>

Copy the code
  • Code interpretation
<template>
  <i class="iconfont" :class="type"></i>
</template>
Copy the code

Because the Icon component itself does not determine which Icon to display, the class of the Icon component needs to be dynamically bound. The type passed by the parent component determines which Icon to use. The values passed by the parent component can be copied from the project to select a specific icon

<style scoped>
@import '//at.alicdn.com/t/font_2648132_8d1o1q9779s.css';
// To import CSS generated for the selected iconfont, see the project for the specific address
.iconfont {
  color: inherit;
  font-size: inherit;
}
</style>
Copy the code

For the CSS of the child components, you need to introduce the CSS generated when the project is created

I want to control the font and color of the Icon component. Therefore, I need to set inherit property in the child component to inherit the style of the parent component. If you want to control other attributes, think of writing

Matters needing attention

In Vue, to ensure that class names overlap between components and cause style conflicts, we can add scoped to component CSS to ensure that each component has its own scope, thus avoiding conflicts. Since the scope of each component is different, why is it possible to set the iconFONT style for the parent component to affect the child component’s root element

To prove that we can change the structure of the Icon component

<template>
  <i class="iconfont" :class="type">
    <span></span>
  </i>
</template>
Copy the code

The conclusion can be drawn from this