1. 程式人生 > >vue組件的那些事($children,$refs,$parent)的使用

vue組件的那些事($children,$refs,$parent)的使用

項目 nbsp text type stop 阻止 spa app 指向

如果項目很大,組件很多,怎麽樣才能準確的、快速的尋找到我們想要的組件了??

1)$refs

首先你的給子組件做標記。demo :<firstchild ref="one"></firstchild>

然後在父組件中,通過this.$refs.one就可以訪問了這個自組件了,包括訪問自組件的data裏面的數據,調用它的函數

2)$children

  他返回的是一個組件集合,如果你能清楚的知道子組件的順序,你也可以使用下標來操作;

for(let i=0;i<this.$children.length;i++){
       console.log(
this.$children[i].msg);輸出子組件的msg數據;
}

接下來就給一個長一點的deno

首先定義一個父組件:parentcomponent,

  在父組件中我又是使用了兩個自組件(假如有一百個自組件)[明確一點,組件只能有一個根節點],根節點是啥,我不知道。。。。。。

<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阻止默認事件(vue的事件處理機制) <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:這是父組件中的內容}                    
                },
                methods:{
                    show_child_of_parents(){
                        //children方式訪問自組件
              
for(let i=0;i<this.$children.length;i++){ console.log(this.$children[i].msg); }
               //通過$ref打標記,訪問子組件  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://www.cnblogs.com/dupd/p/5904109.html

總結一下:

1)組件只能一個根節點

2)可以在自組件中使用this.$parent.屬性值,或者函數

3)在父組件中可以使用this.$refs.組件的標記 訪問子組件,或者this.$children[i].屬性,,訪問子組件的

4)你需要註意this的指向

有圖為證

2017-07-30

技術分享

vue組件的那些事($children,$refs,$parent)的使用