# components/commentslist.vue
# components/blogpost.vue
}
# source.jsconst listeners = {};
const comments = ['comment one', 'comment two', 'comment three', 'comment four', 'comment five'];
const blogposts =
setinterval(() => `)
object.keys(blogposts).foreach(id =>
$` })
}, 5000)
export default ,
getblogpost(id) ,
addchangelistener(listener) , 1000)
listeners[listener] = intervalid
},removechangelistener(listener)
}複製**
從datasource中獲取資料(如:datasource.getcomments()、datasource.getblogpost())
更新外部資料來源中每次更新的資料(handlechange方法)
將更改偵聽器新增到資料來源(mounted方法)
從資料來源中刪除更改偵聽器(beforedestroy方法)
高階元件一步一步演化為了避免**重複,可以將blogpost和commentslist之間的共享邏輯提取到高階元件中,下面是實現步驟。
複製**
# hocs/withsubscription.js
import vue from 'vue'
import commentslist from '~/components/commentslist.vue'
const withsubscription = (component) =>
}}const commentslistwithsubscription = withsubscription(commentslist)
複製**
# hocs/withsubscription.js
import datasource from '../store/source'
import vue from 'vue'
const withsubscription = (component) => ,
methods:
},mounted
() ,
beforedestroy
() })
}export default withsubscription
複製**
- 現在,高階元件返回的新元件需要生命週期鉤子。 handlechange方法保留為空。兩個元件都具有handlechange方法,但是,此方法在每個元件中的實現略有不同
- 高階元件可以接受多個引數。目前,withsubscription僅接受元件作為引數。為了在handlechange中呼叫自定義邏輯,需要第二個引數。第二個引數是應該在每次資料來源更改時呼叫的方法。**如下
複製**
# hocs/withsubscription.js
import datasource from '../store/source'
import vue from 'vue'
const withsubscription = (component, selectdata) =>
})},
data
() },
methods:
},mounted
() ,
beforedestroy
() })
}export default withsubscription
複製**
複製**
複製**# components/blogpost.vue
}
----
# components/commentslist.vue
複製**
"1"/>
---# components/blogpost.vue
}
複製**
# hocs/withsubscription.js
import datasource from '../store/source'
import vue from 'vue'
const withsubscription = (component, selectdata) =>
})},
props: [...originalprops],
data
() },
methods:
},mounted
() ,
beforedestroy
() })
}export default withsubscription
複製**
"1" @click="onclick"/>- 從原元件blogpost獲取props儲存到originalprops中,withsubscription高階元件props接收originalprops的值,以便以後能夠將它們傳遞給blogpost元件
複製**
---# components/blogpost.vue
"$emit('click', 'aloha')">click me!
}複製**
# hocs/withsubscription.js
return vue.component('withsubscription', # <= this line,
})複製**
Vue高階之元件(二)
這一篇主要是講slot。我的另一篇在 另外文章開頭還是要說一下,這一篇文章借鑑了很多 這個博主寫的vue真的很好,包括畫的流程圖,示意圖都很好。官網api的說法是 注意兩點 元件不知道它的掛載點會有什麼內容。掛載點的內容是由的父元件決定的。元件很可能有它自己的模版。為了讓元件可以組合,我們需要一種方...
高階 vue 元件模式 6
之前的五篇文章中,switch元件一直是被視為內部元件存在的,細心的讀者應該會發現,這個元件除了幫我們提供開關的互動以外,還會根據當前toggle的開關狀態,為button元素增加aria expanded屬性,以aira開頭的屬性叫作內容增強屬性,它用於描述當前元素的某種特殊狀態,幫助殘障人士更好...
高階 Vue 元件模式 3
之前一篇文章中,我們雖然將toggle元件劃分為了toggle button toggle on和toggle off三個子元件,且一切執行良好,但是這裡面其實是存在一些問題的 如果熟悉 react 的讀者這裡可能馬上就會想到 hoc 高階元件 的概念,而且這也是 react 中乙個很常見的模式,該...