Vue初體驗之組件

組件定義

組件基本包括2個部份:javascript

  • 頁面結構及樣式
    使用html標籤,對頁面佈局,再經過css美化展現內容
  • 行爲
    經過JS,動態改變頁面內容,觸發事件,實現組件間通訊,使頁面具有交互動做

頁面結構及樣式

這部份內容定義在<template>標籤裏css

<template>
    <div>
        ...
    </div>
</template>
複製代碼

須要注意的是,每一個組件必須只有一個根元素,即:
模板<template>裏只能包含一個兒子元素,孫子元素及後代元素必須包含在這個兒子元素裏。html

行爲

這部分內容定義在<script>標籤裏vue

<script>
// 定義組件
export default {
    name: '組件名', 
    props: ['屬性名A', '屬性名B'], //定夜組件屬性
    data: function() { //組件內部狀態
        return {
            a: ''
        }
    },
    methods: {
        methodA: () => {
            // ...
        }
    },
    //...
}

</script>
複製代碼

實例

項目地址:vue-proj,整個項目很是簡單,用於學習練習,依賴element-ui。
項目中自定義了一個<Article>文章組件,含有2個屬性: 文章名title, 文章內容。組件設計很是簡單,只實現了經過 Prop 向子組件傳遞數據,以下:java

<template>
  <div id="app">
      <Article :title="title" :content="content"></Article>
  </div>
</template>
<script>
import Article from '@/views/Article'
export default {
  name: 'App',
  data: function() {
    return {
      title: 'Hello Vue',
      content: '這是文章的內容哦!!!'
    }
  },
  components: {
    Article
  }
}
</script>
複製代碼

父組件App,經過Article屬性title, content傳遞文章標題和內容,向子組件Article傳數據,顯示效果:git

尾聲

VUE組件很強大,後續會完善項目例子,使用更多組件的用法,更深刻地學習VUEgithub

相關文章
相關標籤/搜索