app.component 和 export default ?


Posted by hoyi-23 on 2021-08-09

(其實我也不太了解這個寫法正不正確
這兩者都是用來建立一個元件,最大的差別是:
app.component 直接在 root 的地方寫入元件,成為 Global Component -- 小Demo適合
import/export default 是將元件寫成分開單一檔案 -- 大專案運用

Global Component

缺點:

  1. Global definitions force unique names for every component
  2. String templates lack syntax highlighting and require ugly slashes for multiline HTML
  3. No CSS support means that while HTML and JavaScript are modularized into components, CSS is conspicuously left out
  4. 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>

相關文章:
多個 Component 元件如何組在一起?
Vue 元件 : Props in & Emit out


#Global-component #Single-file-Component







Related Posts

Callback

Callback

ModernWeb'20 隨筆

ModernWeb'20 隨筆

[Release Notes] 20200924_v1 - Fix blog post serie checkbox bug & add publish type modal

[Release Notes] 20200924_v1 - Fix blog post serie checkbox bug & add publish type modal


Comments