父子組件使用
在工程目錄/src下創(chuàng)建component文件夾,并在component文件夾下創(chuàng)建一個 firstcomponent.vue并寫仿照 App.vue 的格式寫一個組件。
<template>
<div id="firstcomponent">
<h1>I am a title</h1>
<a> {{ author }} </a>
</div>
</template>
<script type="text/javascript">
export default {
data () {
return {
author: "第一個子組件"
}
}
}
</script>
<style>
</style>
image
然后在 App.vue 使用組件
第一步,引入。在<script></script>標簽內的第一行寫:
import firstcomponent from './component/firstcomponent.vue'
第二步,注冊。在<script></script>標簽內的 data 代碼塊后面加上 components: { firstcomponent }
export default {
data () {
return {
msg: 'Hello Vue!'
}
},
components: { firstcomponent }
}
第三步,使用。在<template></template>內加上<firstcomponent></firstcomponent>
<template>
<div id="app">
<img src="./assets/logo.png">
<h1>{{ msg }}</h1>
<firstcomponent></firstcomponent>
</div>
</template>
全局組件
- 使用更為方便,不需要聲明,直接用
- 在main.js中引入一次并使用
Vue.component('組件名', 組件對象) - 所有的組件通過組件名使用