vue組件 $children,$refs,$parent的使用詳解
本文介紹了vue組件 $children,$refs,$parent的使用,分享給大家,也自己留個筆記
如果項目很大,組件很多,怎么樣才能準(zhǔn)確的、快速的尋找到我們想要的組件了??
1)$refs
首先你的給子組件做標(biāo)記。demo :<firstchild ref="one"></firstchild>
然后在父組件中,通過this.$refs.one就可以訪問了這個自組件了,包括訪問自組件的data里面的數(shù)據(jù),調(diào)用它的函數(shù)
2)$children
他返回的是一個組件集合,如果你能清楚的知道子組件的順序,你也可以使用下標(biāo)來操作;
for(let i=0;i<this.$children.length;i++){ console.log(this.$children[i].msg);輸出子組件的msg數(shù)據(jù); }
接下來就給一個長一點的deno
首先定義一個父組件:parentcomponent,
在父組件中我又是使用了兩個自組件(假如有一百個自組件)[明確一點,組件只能有一個根節(jié)點],根節(jié)點是啥,我不知道。。。。。。
<template id="parentcomponent"> <div > <p>this is a parent-component</p> <firstchild ref="f1"></firstchild> <secondchild ref="f2"></secondchild> <button @click='show_child_of_parents'>show child msg</button> </div> </template>
分別給出兩個字組件的定義:(第2個使用的是template,第1個是script)
<script type="text/x-template" id="childOne"> <div> <p>this is first child</p> //使用stop阻止默認(rèn)事件(vue的事件處理機(jī)制) <button @click.stop='getParent'>get parent msg</button> </div> </script> <template id="childSec"> <div> <p>this is second child</p> </div> </template>
組件模板定義好了,就是用:
1)掛在元素:
<script> new Vue({ el:"#app", data:{}, components:{ "parent-component":{ template:'#parentcomponent', data(){ return{msg:'這是父組件中的內(nèi)容'} }, methods:{ show_child_of_parents(){ //children方式訪問自組件 for(let i=0;i<this.$children.length;i++){ console.log(this.$children[i].msg); } //通過$ref打標(biāo)記,訪問子組件 console.log(this.$refs.f1.msg); this.$refs.f1.getParent(); }, }, components:{ 'firstchild':{ template:'#childOne', data(){ return {msg:'這是第一個子組件'}; }, methods:{ getParent(){ let a=1; console.log(a); alert(this.$parent.msg); } }, }, 'secondchild':{ template:'#childSec', data(){ return {msg:"這是第二個組件"}; } } } } } }); </script>
2)使用父組件了
<body> <p><strong>可以通過$refs訪問父組件的子組件</strong></p> <div id="app"> <parent-component></parent-component> </div> </body>
值得注意的是vue2,相比vue1,丟棄了一些東西。。。。、http://chabaoo.cn/article/93467.htm
總結(jié)一下:
1)組件只能一個根節(jié)點
2)可以在自組件中使用this.$parent.屬性值,或者函數(shù)
3)在父組件中可以使用this.$refs.組件的標(biāo)記 訪問子組件,或者this.$children[i].屬性,,訪問子組件的
4)你需要注意this的指向
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
vue前端如何將任意文件轉(zhuǎn)為base64傳給后端
這篇文章主要介紹了vue前端如何將任意文件轉(zhuǎn)為base64傳給后端問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-03-03vue?cli?局部混入mixin和全局混入mixin的過程
這篇文章主要介紹了vue?cli?局部混入mixin和全局混入mixin的過程,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-05-05iview中實現(xiàn)this.$Modal.confirm自定義彈出框換行加樣式
這篇文章主要介紹了iview中實現(xiàn)this.$Modal.confirm自定義彈出框換行加樣式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-09-09vue3使用element-plus搭建后臺管理系統(tǒng)之菜單管理功能
這篇文章主要介紹了vue3使用element-plus搭建后臺管理系統(tǒng)之菜單管理,使用element-plus el-tree組件快速開發(fā)樹形菜單結(jié)構(gòu),el-tree組件中filter-node-method事件便可以實現(xiàn)樹形菜單篩選過濾功能,需要的朋友可以參考下2022-04-04