我們都知道,組件是vue里不可或缺的一部分,當(dāng)有一部分代碼只有內(nèi)容不同,樣式相同且需要重復(fù)使用的時候,如果我們每個頁面都寫這個樣式和代碼,當(dāng)后期樣式或者結(jié)構(gòu)需要調(diào)整的時候,則需要改很多遍,組件解決了這個問題,只需要改一個vue文件,就能修改所有的頁面上使用該組件的樣式。
我們要做的也非常簡單,就是注冊組件,傳遞數(shù)據(jù),使用組件。使用import引入改vue文件,并在components中注冊。
頁面中只需要傳遞數(shù)據(jù)即可。傳遞的數(shù)據(jù)的名字由組件決定。
組件接收的時,需要在props中聲明要接受的數(shù)據(jù)的名字,在html中,就可以像使用data那樣使用父組件傳遞過來的數(shù)據(jù)。聲明的方式除了以下的方式外,還有數(shù)組式接受方法,這種聲明不能規(guī)定傳遞類型和默認(rèn)值,設(shè)置默認(rèn)值必須使用對象的形式,默認(rèn)值為default,其中接受對象形式的數(shù)據(jù)的默認(rèn)值,必須使用函數(shù)的形式。設(shè)置了默認(rèn)值后,當(dāng)父組件傳遞了錯誤的類型或沒有傳遞類型,就會使用默認(rèn)值。
簡單介紹了組件的定義,下面貼一下該組件部分代碼。
html部分
<template>
<ul>
<liv-for="(item, index) insectTable" :key="index"class="respTable">
<divclass="level">{{ index + 1 > 9? index + 1 : '0' + (index + 1) }}</div>
<divclass="bili">
<divclass="clearfix resBilitext">
<divclass="fl frequencyText">{{ item.name }}</div>
<divclass="fr frequency">{{ item.響應(yīng)次數(shù) + '次' }}</div>
</div>
<div>
<el-progress :percentage="item.響應(yīng)率*100" :show-text="false" :color="item.color"></el-progress>
</div>
</div>
</li>
</ul>
</template>
css部分
<style lang='scss' scoped>
/* @import url(); 引入公共css類 */
.respTable {
display: flex;
height: 35px;
margin: 10px 0;
&:nth-of-type(odd)>.level {
background-color: #dfe9ff;
color: #578eff;
}
&:nth-of-type(even)>.level {
background-color: #e1f7fa;
color: #8cdee9;
}
.level {
margin-right: 15px;
height: 35px;
width: 35px;
line-height: 35px;
font-size: 15px;
text-align: center;
border-radius: 5px;
}
.bili {
flex: 1;
.resBilitext {
margin-bottom: 5px;
}
.frequencyText {
font-size: 14px;
}
.frequency {
font-size: 14px;
}
}
}
</style>
下面貼一下使用的效果圖:
該組件接收一個數(shù)組,傳遞名字,次數(shù),響應(yīng)率和進(jìn)度條顏色,序號的顏色由css控制,通過判斷是否是偶數(shù)行或奇數(shù)行展示不同顏色。
下一篇: 沒有了