vue創建自定義組件
文章目錄
- vue創建自定義組件
- 前言
- 一、檔案匯入和組件注冊
- 二、撰寫組件內容
前言
創建自定義組件要先了解檔案匯入和組件注冊,
一、檔案匯入和組件注冊
Vue使用import … from …來匯入組件,庫,變數等,而from后的檔案來源可以是js,vue,json,這個是在webpack.base.conf.js中設定的,其中js和vue是可以省略后綴的,json后綴的檔案不可省略后綴,
我們在檔案夾src/components下創建index.js 和but.vue

撰寫index.js內容:
import testComponent from './but.vue'
const testpon = {
install (Vue) {
Vue.component('testpon', testComponent)
}
}
export default testpon
思考:我們為什么要創建index.js檔案,直接引入but.vue檔案不行嗎,答案是可以的,但是為了后面能夠對test目錄進行資源整合(如components檔案夾中包含許多子組件,我們也想要在全域呼叫這些子組件,那么我們就可以在index.js檔案中把我們需要匯出的組件都在index.js檔案中合并匯出多個組件,讓你寫的多個組件可以在main.js或者其它位置能夠通過index.js統一引入);還有一個作用就是用了index.js,可以將使用組件注冊機制,在vue中注冊為全域組件,方便在其他地方直接呼叫(例如本文index.js中使用了install方法),后面再main.js中引入組件,然后使用Vue.use(組件名)注冊,這樣你就可以在全域中使用這個自定義組件了,
注冊組件:
我們在main.js中匯入檔案夾注冊組件
import testpon from './components'
Vue.use(testpon);
使用import test from './components’時,系統尋找檔案的邏輯程序是:
if(package.json存在 && package.main欄位存在 && package.main指定的js存在) {
取package.main指定的js作為from的來源,即使該js可能格式或內容錯誤
} else if(index.js存在){
取index.js作為from的來源
} else {
取index.vue作為from的來源
}
因此若from后面的來源是檔案夾,那么在package.json存在且設定正確的情況下,會默認加載package.json;
若不滿足,則加載index.js;
若不滿足,則加載index.vue;
這也是系統自動加載的默認順序,同時這也是我們在自定義組件中為什么使用index.js來命名js檔案的原因,
二、撰寫組件內容
1.撰寫but.vue檔案
<template>
<div class="but" :class="[type ,round? 'round': '']" >
<slot></slot>
</div>
</template>
<script>
export default {
data(){
return {
}
},
props: {
type:String,
round:Boolean,
},
}
</script>
<style lang="less">
.but{width: 100px;height: 30px;margin-top: 5px;background:#409EFF;color: #fff; opacity: 0.8 ;border-radius: 5px;margin: auto;text-align: center;line-height: 30px;}
.success{background: #67C23A;color: #fff;}
.danger{background: #F56C6C;}
.round{border-radius: 15px}
</style>
2.使用組件
我在home.vue中使用
<template>
<div class="home">
我是主頁
<testpon class="but">主要按鈕</testpon>
<testpon class="but" type="danger">危險按鈕</testpon>
<testpon class="but" type="success" round>成功按鈕</testpon>
</div>
</template>
效果

實作這個功能用了vue中的props組件之間資料傳遞,還有插槽,
在這里簡單介紹下:
插槽:
當組件渲染的時候, 將會被替換為你所寫的內容,插槽內可以包含任何模板代碼,文本內容,html,甚至其它組件,另外它還有具名插槽:沒有名字的插槽默認名字是default
props:
1.子組件定義props
2子組件規定該屬性用在哪
3.組件呼叫在開始標簽里面傳遞來自父組件的資料
4.props:可以是陣列,可以是物件{屬性名:型別()}
如果不了解props可以查看vue檔案-props詳解
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/304780.html
標籤:其他
上一篇:2021最新~某知名社交平臺的前端工程師筆試題——看看有哪些是你不會的?
下一篇:解決vue的所有相關問題集合
