初識vue 9 元件父子直接訪問

2021-10-09 17:53:07 字數 1895 閱讀 4951

主要使用2個方法$ children、$ refs。

<

!doctype html>

"en"

>

"utf-8"

>

title<

/title>

"../vue.js"

>

<

/script>

<

/head>

>

<

/cpn>

<

/cpn>

<

/cpn>

<

/cpn>

"shu"

>

<

/cpn>

<

/cpn>

"getchild"

>檢視子元件<

/button>

<

/div>

<

/body>

"cpn"

>

}<

/h1>

<

/div>

<

/template>

const cpn=}}

vue.

component

("cpn"

,cpn)

;new

vue(

, methods:},

})<

/script>

<

/html>

這裡使用$children可以訪問到所有子元件的所有資訊,當要具體訪問某乙個子元件裡面的內容的時候,改變 $children陣列下標值就行了,就算只用了乙個元件,也會預設在 $children裡面生成陣列,這個時候就是唯一那個陣列。而且在 $children裡面陣列指向元件的順序就是你在上面html中使用的順序,自上到下。

這裡會發現乙個問題: $children固然可以訪問到子元件,但是因為採用陣列的形式,方法裡面下標是固定的,元件的優點在於復用性,如果在復用的時候改變了順序,或者增加刪除了元件,那麼方法裡面的陣列下標也應該手動去改變,這樣就麻煩了,不利於維護。

所有這裡採用常常是 $refs的方法,只需要在要訪問的地方refs繫結乙個標記用與訪問就行。

採用 $parent方法訪問父元件

採用 $root方法訪問根元件

<

!doctype html>

"en"

>

"utf-8"

>

title<

/title>

"../vue.js"

>

<

/script>

<

/head>

>

<

/cpn>

<

/div>

"cpn"

>

我是cpn元件<

/h2>

<

/ccpn>

<

/div>

<

/template>

"ccpn"

>

我是子元件<

/h2>

"btnclick"

>按鈕<

/button>

<

/div>

<

/template>

newvue(,

components:},

components:}}

}}}}

)<

/script>

<

/body>

<

/html>

這裡的 $parent,不是陣列形式,主要是因為乙個子元件只有乙個父元件,但是乙個父元件能有多個子元件。所以 $children是陣列形式。

學習Vue(9) 元件

元件 component 是 vue.js 最強大的功能之一。元件可以擴充套件 html 元素,封裝可重用的 要使用元件,就需要先註冊乙個元件,下面是註冊乙個全域性元件的語法 vue.component tagname,options 解釋說明 所有例項都能夠使用的元件就是全域性元件,註冊在例項之外...

VUE (9)元件 props資料傳遞

本篇資料來於官方文件 簡單來說,更適合新手閱讀 二十六 props資料傳遞 是孤立的,簡單的來說,元件和元件之間,即使有同名屬性,值也不共享。add del div var vm new vue button data function del button data function script...

VUE (9)元件 props資料傳遞

本篇資料來於官方文件 簡單來說,更適合新手閱讀 二十六 props資料傳遞 是孤立的,簡單的來說,元件和元件之間,即使有同名屬性,值也不共享。add del div var vm new vue button data function del button data function script...