在使用vue-cli腳手架構建項目時,組件的使用步驟大致是:創建組件component,編寫模板template,拋出組件給項目export,引入組件import,拋出組件給頁面export。
一、創建組件
在componets文件夾里創建新的組件文件newVue.vue,注意后綴名為.vue
注意:組件名稱不能使用html的自有標簽或javascript的關鍵字,例如:head.vue,new.vue這樣的組件名稱是不符合規范的,加載的時候也會出現問題。
二、編寫組件內的模板內容和樣式
template是模板的意思,模板內容就是組件將展示的具體內容
<template> <div>這里是模板內容</div> </template>
<style scoped>
//這里可以編寫樣式
</style>
注意:模板內容只能有一個頂層html標簽,例如:上面代碼里將div作為頂層標簽,那么所有的模板內容都必須寫在這個div內部
三、拋出組件給vue項目
通過export將組件拋出給vue項目,並將組件命名為newVue
<template>
<div>這里是模板內容</div>
</template>
<script>
export default {
name: 'newVue'
}
</script>
<style scoped>
</style>
四、引入組件到主組件,並將引入的組件拋出給主組件
import newVue from '@/components/newVue'
通過import引入組件,再通過export將引入的組件拋出給主組件,拋出多個組件用逗號隔開即可
主組件就可以通過自定義標簽調用:
<newVue></newVue>
<template> <div id="app"> <newVue></newVue> <router-view/> </div> </template> <script> import newVue from '@/components/newVue' export default { components:{ newVue } } </script>