組件對於vue來講很是重要,學習學習了基礎vue後,再回過頭來把組件弄透!css
組件意味着協同工做,一般父子組件會是這樣的關係:組件 A 在它的模版中使用了組件 B 。html
它們之間必然須要相互通訊:父組件要給子組件傳遞數據,子組件須要將它內部發生的事情告知給父組件。vue
在 Vue.js 中,父子組件的關係能夠總結爲 props down, events up 。java
父組件經過 props 向下傳遞數據給子組件,子組件經過 events 給父組件發送消息。api
看看它們是怎麼工做的。app
組件實例的做用域是孤立的。這意味着不能(也不該該)在子組件的模板內直接引用父組件的數據。要讓子組件使用父組件的數據,咱們須要經過子組件的props選項。學習
子組件要顯式地用 props
選項聲明它期待得到的數據:this
js: spa
Vue.component('child', { / 聲明 props props: ['message'], // 就像 data 同樣,prop 能夠用在模板內 // 一樣也能夠在 vm 實例中像 「this.message」 這樣使用 template: '<span>{{ message }}</span>' })
<child message="hello!"></child>
這個是vue官網上給的方法調用,咱們看看頁面上怎麼使用。3d
子組件 main_Header.vue
<template> <div> <div>{{count}}</div> <div v-for="(item, index) in list">{{item}}</div> <button v-on:click="sendMsg">向父組件傳參</button> <!-- 這裏用簡單的綁定方法觸發傳參--> </div> </template> <script> export default { name: 'main_header', props: ['count', 'list'], methods: { sendMsg: function () { //傳參方法 this.$emit('headCallBack', '子組件的參數內容'); //第一個參數是父組件中v-on綁定的自定義回調方法,第二個參數爲傳遞的參數 } } }; </script> <style> </style>
父組件 App.vue
<template> <div id="app"> <img src="./assets/logo.png"> <div>子組件傳過來的內容:{{msg}}</div> <mainHeader :count="count" :list="list" v-on:headCallBack="headCall"></mainHeader> <!--經過v-on綁定方法,headCallBack爲子組件中$emit()中第一個參數,headCall爲回調方法,參數就傳入這個方法中,看下面的方法--> <router-view/> </div> </template> <script> import mainHead from './components/header/main_header'; var data = { list: ['java', 'html', 'css', 'js'] }; export default { name: 'app', data: function () { return { count: 0, list: data.list, msg: '' }; }, components: { mainHeader: mainHead }, methods: { addCount: function () { let _this = this; setInterval(function () { _this.count++; }, 1000); }, headCall: function (msg) { //回調方法,接收子組件傳的參數 this.msg = msg; } }, mounted: function () { this.$nextTick(function () { this.addCount(); }); } }; </script>
效果: