1. 程式人生 > >Vue:如何在vue-cli中建立並引入自定義元件

Vue:如何在vue-cli中建立並引入自定義元件

一、建立並引入一個元件

1、建立元件

vue-cli中的所有元件都是存放在components資料夾下面的,所以在components資料夾下面建立一個名為First.vue的自定義元件:

<template>
    <div>
        <h1>{{msg}}</h1>
    </div>
</template>
<script>

// 1、export 表示匯出,在自定義元件裡面使用export default匯出  
export default {
    // name 表示設定別名,可以不設定,建議和元件的名稱一致
name:"First", data(){ return{ msg:"First Vue" } } } </script>

2、在App.vue元件裡面引用First.vue元件

1、在<script>標籤裡面使用import匯入自定義的標籤:

// 1、匯入自定義元件 First即First.vue元件裡面設定的name值
import First from "./components/First"

2、在export裡面新增自定義元件:

 // 2、新增自定義元件
  components:{
    First
  }

 3、在<template>標籤裡面引入自定義元件:

<template>
  <div id="app">
    <img src="./assets/logo.png">
    <!-- <router-view/> -->
    <!--3、引用自定義元件-->
    <First></First>
  </div>
</template>

 完整程式碼如下:

<template>
  <div 
id="app"> <img src="./assets/logo.png"> <!-- <router-view/> --> <!--3、引用自定義元件--> <First></First> </div> </template> <script> // 1、匯入自定義元件 First即First.vue元件裡面設定的name值 import First from "./components/First" export default { name: 'App', // 2、新增自定義元件 components:{ First } } </script> <style> #app { font-family: 'Avenir', Helvetica, Arial, sans-serif; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; text-align: center; color: #2c3e50; margin-top: 60px; } </style>

 效果:

二、引入巢狀元件

在上面的示例中,只是在App.vue中引入了單一的元件,如何引入巢狀元件呢?即First.vue元件裡面又引用了自定義元件,這時該如何在App.vue元件裡面引入呢?

1、先定義Second.vue自定義元件:

<template>
    <div>
        <h1>{{secondMsg}}</h1>
    </div>
</template>

<script>
export default {
    // name 表示設定別名,可以不設定,建議和元件的名稱一致
    name :"Second",
    data(){
       return{
           secondMsg:"Second vue"
       }
    }
}
</script>

2、在First.vue元件中引用Second.vue元件

在First.vue中引用Second.vue元件和在App.vue中引入First.vue元件是一樣的,完整程式碼如下:

<template>
    <div>
        <h1>{{msg}}</h1>
        <!--3、引用second.vue元件-->
        <Second></Second>
    </div>
</template>
<script>
// 1、使用import匯入Second.vue
import Second from './Second';
// export 表示匯出
export default {
    // name 表示設定別名,可以不設定,建議和元件的名稱一致
    name:"First",
    data(){
        return{
            msg:"First Vue"
        }
    },
    // 2、新增自定義元件元件
    components:{
        Second
    }
}
</script>

3、在App.vue中引入巢狀元件

First.vue中引入了Second.vue元件以後,可以把First.vue元件看成是一個元件了,所以在App.vue中引入的時候程式碼是一樣的:

<template>
  <div id="app">
    <img src="./assets/logo.png">
    <!-- <router-view/> -->
    <!--3、引用自定義元件-->
    <First></First>
  </div>
</template>

<script>
// 1、匯入自定義元件 First即First.vue元件裡面設定的name值
import First from "./components/First"
export default {
  name: 'App',
  // 2、新增自定義元件
  components:{
    First
  }
}
</script>

<style>
#app {
  font-family: 'Avenir', Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

4、效果