若是項目很大,組件不少,怎麼樣才能準確的、快速的尋找到咱們想要的組件了??vue
$refs
首先你的給子組件作標記。demo :<firstchild ref="one"></firstchild>
而後在父組件中,經過this.$refs.one就能夠訪問了這個自組件了,包括訪問自組件的data裏面的數據,調用它的函數
注意:
ref 被用來給元素或子組件註冊引用信息。引用信息將會註冊在父組件的 $refs 對象上。若是在普通的 DOM 元素上使用,引用指向的就是 DOM 元素; 若是用在子組件上,引用就指向組件實例
當 v-for 用於元素或組件的時候,引用信息將是包含 DOM 節點或組件實例的數組數組
$children
他返回的是一個組件集合,若是你能清楚的知道子組件的順序,你也能夠使用下標來操做;函數
3.$parent在子組件中調用父組件的方法或得到其數據this
<template> <div id='parents'> <p>我是父組件 <button @click="click1hanlde">獲取子組件1的數據與方法</button> <button @click="click2hanlde">獲取全部子組件的數據和方法</button></p> <childCom1 ref="childCom1"></childCom1> <childCom2 ref="childCom2"></childCom2> </div> </template> <script> import childCom1 from './childCom1.vue' import childCom2 from './childCom2.vue' export default { components:{ childCom1, childCom2 }, data() { return { ParentData:'AAA' }; }, methods:{ click1hanlde(){ console.log(this.$refs.childCom1.children_data);//children_data1 this.$refs.childCom1.children_fun(); }, click2hanlde(){ for(let i=0;i<this.$children.length;i++){ // console.log(this.$children.length);//2個組件 childCom1 childCom2 console.log(this.$children[i].children_data); //children_data2 this.$children[i].children_fun(); } }, showParentData(){ console.log(this.ParentData) } } }; </script>
<template> <div id='children1'> <p>我是子組件1: <button @click="getParent_fun">獲取父組件的數據和方法 </button></p> </div> </template> <script> export default { data() { return { children_data:'children_data1', }; }, methods:{ children_fun(){ console.log('我是子組件1的方法') }, getParent_fun(){ this.$parent.showParentData(); } } }; </script>
<template> <div id='children2'> <p>我是子組件2</p> </div> </template> <script> export default { data() { return { children_data:'children_data2', }; }, methods:{ children_fun(){ console.log('我是子組件2的方法') } } }; </script>