前端最基礎的就是 HTML+CSS+Javascript
。掌握了這三門技術就算入門,但也僅僅是入門,如今前端開發的定義已經遠遠不止這些。前端小課堂(HTML/CSS/JS
),本着提高技術水平,打牢基礎知識的中心思想,咱們開課啦(每週四)。html
組件開發在 Vue 使用中很常見,好處有不少 解耦、並行開發、複用 等等。前端
使用上也很簡單,咱們能夠對比一下 elementUI 的 el-input 和 原生的 input。vue
<el-input v-model="val"> <input v-model="val">
組件能夠理解爲可複用的 Vue 實例,因此與 new Vue
接收相同的選項,例如 data
、computed
、watch
、methods
以及生命週期鉤子等。vuex
經過 Vue.component
進行全局註冊,註冊以後能夠用任何地方,包括組件樹中的全部子組件的模板中。segmentfault
// 定義一個名爲 v-input 的全局組件 Vue.component('v-input', { data: function () { // data 必須是一個函數 // 這樣才能在多個位置使用時,多個組件不存在引用關係 return { val: '' } }, // template 必須有一個根節點。 // 每一個組件必須只有一個根元素(every component must have a single root element ) template: ` <div> <input v-model="val"> val: {{val}}. </div> ` })
局部註冊就是在 components
裏面寫,只能用在當前組件模板中。微信
new Vue({ el: '#app', components: { 'v-input': { data: function () { // data 必須是一個函數 // 這樣才能在多個位置使用時,多個組件不存在引用關係 return { val: '' } }, // template 必須有一個根節點。 template: ` <div> <input v-model="val"> val: {{val}}. </div> ` } })
父組件:app
<v-avatar avatar="https://www.lilnong.top/favicon.ico"></v-avatar>
子組件:函數
Vue.component('v-avatar', { props: ['avatar'], template: '<img :src="avatar">' })
測試地址:https://www.lilnong.top/static/html/sf-a-1190000022616927-vue-emit.html
父組件:測試
<v-input :value="val" @input="val = $event"></v-input>
子組件:this
Vue.component('v-input', { props: ['val'], template: '<input :value="val" @input="emitInput">', methods:{ emitInput(e){ this.$emit('input', e.target.value) } } })
通常在咱們使用中 v-model
的方式更經常使用
<input v-model="val"> <el-input v-model="val"></el-input>
那麼 v-model
是如何實現父子組件通訊的呢?
原生 DOM<input v-model="val">
等價於 <input v-bind:value="val" v-on:input="val = $event.target.value" >
自定義組件<v-input v-model="val"></v-input>
等價於<v-input :value="val" @input="val = $event"></v-input>
從上面咱們能夠看到, v-model
相似於語法糖,本質上是經過綁定 value 和 input。
.sync
修飾符<text-document v-bind:title.sync="doc.title"></text-document>
等價於
<text-document v-bind:title="doc.title" v-on:update:title="doc.title = $event" ></text-document>
子組件中更新時: this.$emit('update:title', newTitle)
在有些狀況下,咱們須要對一個 prop 進行「雙向綁定」。
不幸的是,真正的雙向綁定會帶來維護上的問題,由於子組件能夠變動父組件,且在 父組件和子組件都沒有明顯的變動來源。
推薦以this.$emit('update:myPropName')
的模式觸發事件取而代之。