寫在前面
因?yàn)閷?duì)Vue.js很感興趣,而且平時(shí)工作的技術(shù)棧也是Vue.js,這幾個(gè)月花了些時(shí)間研究學(xué)習(xí)了一下Vue.js源碼,并做了總結(jié)與輸出。
文章的原地址: https://github.com/answershuto/learnVue 。
在學(xué)習(xí)過程中,為Vue加上了中文的注釋 https://github.com/answershuto/learnVue/tree/master/vue-src ,希望可以對(duì)其他想學(xué)習(xí)Vue源碼的小伙伴有所幫助。
可能會(huì)有理解存在偏差的地方,歡迎提issue指出,共同學(xué)習(xí),共同進(jìn)步。
什么是Vue組件?
組件 (Component) 是 Vue.js 最強(qiáng)大的功能之一。組件可以擴(kuò)展 HTML 元素,封裝可重用的代碼。在較高層面上,組件是自定義元素,Vue.js 的編譯器為它添加特殊功能。在有些情況下,組件也可以是原生 HTML 元素的形式,以 is 特性擴(kuò)展。
Vue組件間通信
父組件向子組件通信
方法一:props
使用 props ,父組件可以使用props向子組件傳遞數(shù)據(jù)。
父組件vue模板father.vue
<template> <child :msg="message"></child></template><script>import child from './child.vue';export default { components: { child }, data () { return { message: 'father message'; } }}</script>子組件vue模板child.vue
<template> <div>{{msg}}</div></template><script>export default { props: { msg: { type: String, required: true } }}</script>方法二 使用$children
使用 $children 可以在父組件中訪問子組件。
子組件向父組件通信
方法一:使用 vue事件
父組件向子組件傳遞事件方法,子組件通過$emit觸發(fā)事件,回調(diào)給父組件。
父組件vue模板father.vue
<template> <child @msgFunc="func"></child></template><script>import child from './child.vue';export default { components: { child }, methods: { func (msg) { console.log(msg); } }}</script>子組件vue模板child.vue
<template> <button @click="handleClick">點(diǎn)我</button></template><script>export default { props: { msg: { type: String, required: true } }, methods () { handleClick () { //........ this.$emit('msgFunc'); } }}</script>方法二: 通過修改父組件傳遞的props來修改父組件數(shù)據(jù)
這種方法只能在父組件傳遞一個(gè)引用變量時(shí)可以使用,字面變量無法達(dá)到相應(yīng)效果。因?yàn)轱嬘米兞孔罱K無論是父組件中的數(shù)據(jù)還是子組件得到的props中的數(shù)據(jù)都是指向同一塊內(nèi)存地址,所以修改了子組件中props的數(shù)據(jù)即修改了父組件的數(shù)據(jù)。
但是并不推薦這么做,并不建議直接修改props的值,如果數(shù)據(jù)是用于顯示修改的,在實(shí)際開發(fā)中我經(jīng)常會(huì)將其放入data中,在需要回傳給父組件的時(shí)候再用事件回傳數(shù)據(jù)。這樣做保持了組件獨(dú)立以及解耦,不會(huì)因?yàn)槭褂猛环輸?shù)據(jù)而導(dǎo)致數(shù)據(jù)流異常混亂,只通過特定的接口傳遞數(shù)據(jù)來達(dá)到修改數(shù)據(jù)的目的,而內(nèi)部數(shù)據(jù)狀態(tài)由專門的data負(fù)責(zé)管理。
新聞熱點(diǎn)
疑難解答
圖片精選