(其實我也不太了解這個寫法正不正確
這兩者都是用來建立一個元件,最大的差別是:
app.component 直接在 root 的地方寫入元件,成為 Global Component -- 小Demo適合
import/export default 是將元件寫成分開單一檔案 -- 大專案運用
Global Component
缺點:
- Global definitions force unique names for every component
- String templates lack syntax highlighting and require ugly slashes for multiline HTML
- No CSS support means that while HTML and JavaScript are modularized into components, CSS is conspicuously left out
- No build step restricts us to HTML and ES5 JavaScript, rather than preprocessors like Pug (formerly Jade) and Babel
// Create a Vue application
const app = Vue.createApp({});
// Define a new global component called button-counter
app.component('button-counter', {
data() {
return {
count: 0
}
},
template: `
<button @click="count++">
You clicked me {{ count }} times.
</button>`
})
app.mount('#app');
Single File Component
這個就需要了解遺下 ES6 的模組使用
import / export
下面兩篇文章皆是用 Single File Component
寫法
檔案: component.vue
<template lang="pug"> //可以設定想要用其他syntax
p{{greet}}
other-component
</template>
<script>
import OtherComponent from "./OtherComponent.vue"
export default {
component:{
OtherComponent
},
data(){
return{ greet: "Hello!"}
}
}
</script>
<style scoped>
//scoped設定只會套用到現在的component
//也可以加 lang="scss" 來設定寫法
p{
color: red;
}
</style>