vue封装组件,通过传入参数,修改组件样式

意义

vue被广大前端推崇很重要一点就是组件封装,但是在组件封装的时候,组件可能在各处都要用到,但是在各处的样式可能不太一样,例如:按钮组件,这时怎么办,难道不同样式但是结构相同的组件进行多次封装么?很明显是很不合算的。

用代码说话

父组件:

<template>
  <el-container class="layout_container">
    <el-header height="auto"><header-top></header-top></el-header>
    <el-container>
      <el-aside width="auto"><aside-left></aside-left></el-aside>
      <el-main>
        <zonghe-nengli></zonghe-nengli>
       /重点看此处:
        <my-button
          :title="biaoti"
          :color="activeColor"
          :size="fontSize"
        ></my-button>
        ///
        <skill-hot></skill-hot>
        <learning-path></learning-path>
        <bar-chart></bar-chart>
        <radar></radar>
        <tupu-fenxi></tupu-fenxi>
      </el-main>
    </el-container>
  </el-container>
</template>
<script>
import HeaderTop from "../../components/layout/header";

import MyButton from "../../components/common/button";

import AsideLeft from "../../components/layout/aside";
import ZongheNengli from "../../components/common/zonghenengli";
import Radar from "../../components/common/radar";
import TupuFenxi from "../../components/common/tupufenxi";
import SkillHot from "../../components/putong/skillhot";
import LearningPath from "../../components/putong/learningpath";
import BarChart from "../../components/common/barchart";
export default {
    
    
  components: {
    
    
    HeaderTop,
    AsideLeft,
    ZongheNengli,
    Radar,
    TupuFenxi,
    SkillHot,
    LearningPath,
    BarChart,
    MyButton,
  },
  data() {
    
    
    return {
    
    
    ///
      biaoti: 20,
      activeColor: "black",
      fontSize: 30,
   ///
    };
  },
  created() {
    
    },
  methods: {
    
    },
  computed: {
    
    },
};
</script>
<style scoped>
.layout_container {
    
    
  height: 100%;
}
.el-aside {
    
    
  margin-top: 21px;
  background: #ffffff;
  box-shadow: 0px 1px 13px 0px rgba(0, 0, 0, 0.35);
}
.el-main {
    
    
  margin-top: 40px;
  margin-left: 37px;
  background-color: burlywood;
}
</style>

子组件(重点看看):

<template>
  <div class="button_container" :style="{color:activeColor,fontSize:fontSize + 'px'}">
    {
    
    {
    
     title }}
  </div>
</template>
<script>
export default {
    
    
  /接受传过来的参数
  props: ["title","color","size"],
  data() {
    
    
    return {
    
    
      activeColor: this.color,
      fontSize: this.size,
    };
  },
  created() {
    
    
    
  },
  methods: {
    
    },
  computed: {
    
    },
};
</script>
<style scoped>
.button_container {
    
    
  width: 207px;
  height: 60px;
  margin: 35px;
  line-height: 60px;
  text-align: center;
  background: #2e5afb;
  box-shadow: 3px 8px 17px 1px rgba(46, 90, 251, 0.6);
  border-radius: 6px;
}
</style>

效果图:
在这里插入图片描述

想要封装可以动态改变样式的组件,必须得熟练掌握vue组件的class和style绑定,这样才能游刃有余

猜你喜欢

转载自blog.csdn.net/weixin_43131046/article/details/114261885