超簡單的Vue.js組件入門javascript
在vue開發中,爲了能讓一些頁面中的元素使用性和複用性更高咱們能夠將一些html元素封裝成可用的一些組件或者是模板。而後經過嵌套的方式進行在頁面中嵌套使用,實現一種積木式編程。html
經過Vue.extend()聲明組件
Vue.extend是vue提供出來給咱們實現組件的函數vue
//組裝組件(聲明組件) var MyComponent = Vue.extend({ //被封裝的html內容 template: '<div>This is your first vue components!</div>', //綁定在這個組件內的數據 data: '', //監聽這個組件的事件的方法 methods: '', //屬性,一般被用來進行數據的通訊 props: '' });
註冊組件——向vue核心容器註冊這個組件
這是爲了讓vue更好的管理組件(複用和刪除)java
Vue.component('my-component', MyComponent); //註冊組件,傳入別名(my-component)和組件名稱(MyComponent)
初始化Vue.js的管理邊界編程
var vm = new Vue({ el: '#app', });
裝入組件app
在頁面中嵌入 <div id="app"> <my-component></my-component> </div>
簡單四步,完成一個組件的裝載流程 :)模塊化
Q1: 組件化除了視圖複用性更高之外的特殊做用?
讓一個組件具備自身獨立的功能——模塊化!>_<!!!函數
Q2: 如何在組件中進行js事件的綁定以及數據綁定?組件化
var MyComponent = Vue.extend({ template: '<p></p>', methods: { searchList: function() { console.log('Your cause an event!'); }, }, ready: function() { //在模塊準備就緒時觸發 console.log("Loading Complete!"); }, data: function() { //這裏進行數據綁定,注意,爲了方便數據的預處理,組件中的data是經過函數返回的對象 return { result: '' } } });
Q3:那都是經過一對一的綁定來實現數據同步的嗎?
No!有種羈絆叫作組件嵌套this
經過組件之間的相互嵌套來達到組件內部的數據同步,而且這樣的機制有利於開發功能性組件(如輪播圖,搜索框,評論區等)
父子組件通訊
父組件傳值給子組件——只要data發生改變
父組件的view發生改變,子組件的view也發生改變
值傳到子組件的方式是經過props屬性
子組件經過props數據進行view同步
js腳本
var child = Vue.extend({ template: '<p>{{ content }}</p>', props: ['content'] }); var Father = Vue.extend({ template: '<div><child :content='message'></child><input type="text" @change="sendMessage( $event );"/></div>',//將message代理到content屬性中 data: function() { return { message: '' } }, method: { sendMessage: function( event ) { //觸發事件的事件列表 this.message = event.target.value; //改變message的值 } } }); //註冊父組件 Vue.component('father-component', Father); //定義邊界 var vm = new Vue({ el: '#app' });
html
<div id="app"> <father-component></father-component> </div>
運行效果:
兄弟組件通訊
兄弟組件的通訊是經過一個共同的父組件或者邊界來進行橋接
建立兄弟組件
經過父組件「橋樑函數」的「分發」,子組件分別獲得model,並同步到本身的view中去
js腳本
//孿生哥哥 var twinsCompOld = Vue.extend({ template: '<p>I am the old brother, my age is {{ title }}<input type="number" @change="GrowUp( $event )"></p>', props: ['title', 'bridge'],//哥哥傳入控制年齡增加的回調函數 methods: { GrowUp: function(event) { this.bridge(event.target.value);//將當前的年齡傳入橋樑 } } }); //孿生弟弟 var twinsCompLittle = Vue.extend({ template: '<p>I am the little brother, my age is {{ title }}</p>', props: ['title']//同步年齡 }); //父親 var Father = Vue.extend({ template: '<div>{{ say }}<oldBrother :title="sonAge" :bridge="sendMessage"></oldBrother><littleBrother :title="sonAge"></littleBrother></div>', components: { 'oldBrother': twinsCompOld, 'littleBrother': twinsCompLittle }, data: function() { var self = this; //由於執行這個函數的是子組件,所以須要將父組件的指針保存一下 return { say: 'Daddy love you!', sonAge: 0, sendMessage: function( content ) { //橋樑函數 self.sonAge = content; return self.sonAge;//兒子的年齡變化了 } } } }); //註冊父組件 Vue.component('father-component', Father); //定義邊界 var vm = new Vue({ el: '#app' });
html:
<body> <father-component></father-component> </body>
運行效果: