1. 程式人生 > 實用技巧 >.vue 檔案介紹

.vue 檔案介紹

.vue檔案介紹

  • .vue檔案(元件)的三大部分

    • <template></template>

    • <script></script>
    • <style></style>

快捷鍵sca+回車 或者<>+ 回車

使用元件的注意事項:

​   1.裡面 必須用 根標籤包裹 (就是template下面只有一個div)

      <template>
          <div>
              <h1>我是元件1</h1>
          </div>  
      </template>

​   2.程式碼寫到exprot default裡面

      <script>
        export default {
  
        };
      </script>   
 3.<style></style>標籤:
.vue檔案的樣式檔案

    
    
  • 詳細過程:

    ​ 第一步:在components資料夾下,新建元件

    • sca

    • 建立子元件

      程式碼如下:

      <template>
          <div>
              <h3>我是hello vue</h3>
              <button @click="tips">點我呀</button>
          </div>
      </template>
      
      <script>
      export default {
          methods:{
              tips(){
                  alert('我被點了');
              }
          }
      
      }
      </script>
      
      <style>
      
      </style>
      

      第二步:

    1. 來到 main.js

    2. 使用import 名字 from '元件路徑'引入

    3. 呼叫Vue.componment('元件id',元件名字)來註冊 (Vue的V是大寫)

    4. 在需要用到這個元件地方,寫元件id的標籤就可以了

      程式碼如下:

      // 進入main.js 檔案
      import Vue from 'vue'
      import App from './App.vue'
      // 匯入子元件 hellovue
      import hellovue from './components/hellovue.vue'
      
      //註冊元件
      Vue.component('hello',hellovue);
      
      // 是否列印提示資訊,可以刪除
      // 刪除的話,預設值為true
      Vue.config.productionTip = false
      
      // new Vue({
      //   render: h => h(App),
      // }).$mount('#app')
      
      // 上面註釋程式碼 相當於如下:
      new Vue({
        el: '#app',
        // 把App元件渲染出來
        render: h => h(App),
      })
      

註冊區域性元件

  • 顧名思義:在哪註冊,就在哪可以使用
  • 用法:
    1. 在需要用的地方,引包import 名字 from '元件路徑'引入`
    2. export default裡寫一個屬性:componments傳入一個物件,物件裡寫 這個元件名
    3. 元件名叫什麼,那麼在html 裡就可以寫這個名字的標籤

程式碼如下:

<template>
  <div>
    <h1>這是我建立的第一個cli專案</h1>
    <hello></hello>
    <localvue></localvue>
    <localvue></localvue>

  </div>
</template>

<script>

// 註冊區域性元件,在哪註冊,在哪使用   在App.vue裡註冊的只能在App.vue裡面使用
import localvue from './components/localvue.vue'
export default {
  components:{
    localvue
  }

}
</script>

<style>
    
</style>

元件的name屬性

  1. 直接在元件的內部寫name:值即可

  2. 不能用中文

  3. 寫了之後,chrome的vue外掛中可以看到這個名字,更加利於檢索,利於編碼

    程式碼如下:

    <script>
    export default {
    	name:'hellovue'
    }
    </script>