Vue基礎 - 組件

組件的概念

組件至關於積木玩具,許許多多不一樣的積木就能夠拼裝成汽車,城堡,動物等等各類各樣的玩具模型,所以不一樣的組件相互組合起來就能夠產生一個組合模板。在網頁開發中很是實用。javascript

註冊基本組件

組件也分爲全局組件和局部組件。html

全局組件
<div id="app">
    <mycomponent></mycomponent>
</div>
<!-- js -->
Vue.component('mycomponent',{
	template : '<div>這是一個自定義組件</div>'
});
複製代碼

在Vue中經過component()來定義組件,第一個參數爲組件名稱,第二個爲組件對象,其中包含了data,templat等對象。java

局部組件

顧名思義,局部組件只能在Vue實例中的使用,經過new Vue中的components對象來實現:bash

new Vue({
    el : '#app',
    data : {},
    methods : {},
    components : {
        home : {
            template : '<div>這是局部組件</div>'
        }
    },
});
複製代碼
template模板的要求

1.模板下只能擁有一個根元素,若是多出來,會報錯如下信息app

[Vue warn]: Error compiling template:
Component template should contain exactly one root element. If you are using v-if on multiple elements, use v-else-if to chain them instead.

1  |  <div>這是局部組件</div><div></div>
   |                   ^^^^^^^^^^^
found in
---> <Home>
       <Root>
複製代碼

2.組件中的data和el必須是一個函數,經過返回值,爲何是函數形式呢?主要仍是由於像Vue那樣傳遞的話,會形成當一個組件中的某個值修改的時候,全部值都被修改了。函數

3.在HTML中,組件可能會受到一些限制,好比在表格中,若是使用自定義組件的話,它會被認爲是無效的內容。下面列出一些常見會出現問題的標籤:post

  • a 不能包含其它的交互元素(如按鈕,連接)
  • ul 和 ol 只能直接包含 li
  • select 只能包含 option 和 optgroup
  • table 只能直接包含 thead, tbody, tfoot, tr, caption, col, colgroup
  • tr 只能直接包含 th 和 td

所以,咱們須要使用is屬性才能正常使用。this

<table> 
	<tr is="mycomponent"></tr> 
</table>
複製代碼

組件的交配

在實際開發中組件之間的配合使用時必然的,所以父組件須要給子組件發數據,子組件也須要將本身發生的事件傳遞給父組件,在開發中,咱們定義模塊除了更好的對代碼分塊,利於閱讀和維護外,還能減小一些代碼的重複,來達到複用。所以,組件裏面的數據就須要咱們開發者本身傳遞進去。spa

傳遞數據給組件,實現組件的複用性

在組件傳遞參數中,咱們可使用props來傳遞參數,.net

1.定義一個組件模板:

<!-- 組件模板的定義 -->
    <template id="fucomponent">
        <div>
            文本是:{{str}}
        </div>
    </template>
複製代碼

2.綁定組件

components : {
    fucp : {
        template : '#fucomponent',
            //傳遞參數
            props: ["str","str1"],
                data () {
                return {
                }
            }
    },
}
複製代碼

3.使用組件,而且傳遞參數

<fucp str = '我是props傳遞的參數'></fucp>
複製代碼
prop的參數類型

在傳遞數中prop是能夠規定參數的類型的,須要將props轉換成對象的形式

props : {
    text : String,
}
複製代碼
子組件傳遞給父組件

自組件傳遞給父組件可使用emit和on的方式進行溝通

1.建立子組件

<template>
    <div>
        <!-- 開始定義組件 -->
        <button @click="postSj">上傳子組件信息</button>
    </div>
</template>
<script>
export default{
    name : 'child',
    methods: {
        postSj : function (){
            this.$emit('getmsg','我是子組件傳遞過來的組件');
        }
    }
}
</script>
<style>
</style>
複製代碼

2.建立父組件

<template>
  <div class="hello">
    <h4>parent</h4>
    <h5>title的值:{{title}}</h5>
    <child @getmsg='getmsg'></child>
  </div>
</template>

<script>
import child from './child'
export default {
  name: 'HelloWorld',
  data () {
    return {
      title : ''
    }
  },
  methods : {
    getmsg(res){
      this.title = res;
    }
  },
  components: {
    child
  },
}
</script>
複製代碼

實例:

Vue界面
相關文章
相關標籤/搜索