Vue 中元件概念

2021-09-07 19:19:17 字數 2585 閱讀 2147

1 為了能在模板中使用,元件必須先註冊以便 vue 能夠識別。這裡有兩種元件的註冊型別:全域性註冊區域性註冊

1.1 全域性註冊是通過vue.component來向vue註冊,例子

vue.component('

my-component-name

', )

全域性註冊的元件可以用在其被註冊之後的任何 (通過new vue) 新建立的 vue 根例項,也包括其元件樹中的所有子元件的模板中。

1.2 區域性註冊,先聲名乙個區域性元件,在 js 檔案中直接用變數接收物件

var comp =
在根例項中使用 components 屬性引入區域性元件。

new

vue()

引入區域性元件後就可以在模板中使用子元件了。

2 父元件向子元件傳遞資料方法,通過 prop 向子元件傳遞資料,父元件資料通過繫結子元件的屬性向子元件傳遞資料,在子元件的模板中就可以使用該屬性。即成為了子元件的資料屬性。

prop 是你可以在元件上註冊的一些自定義屬性。當乙個值傳遞給乙個 prop 屬性的時候,它就變成了那個元件例項的乙個屬性。例子如下:

2.1 定義乙個子元件

vue.component('

list-item',}

",props:[

'content']

});

props 表明子元件接受父元件通過 content 屬性傳遞過來的資料。

此時子元件的 template 就可以使用 props 中聲名的屬性了。該屬性也是子元件的資料屬性。

2.2 在父元件的模板中使用聲名的元件。

將父元件中的 item 資料繫結到子元件的 content 屬性上。

至此就完成了父元件向子元件傳遞資料的功能。

完整**如下:

"en

">"

root

">

"inputvalue

">

"additem

">點我提交

view code

3 通過事件向父元件傳送訊息

3.1 子元件觸發父元件的乙個事件,我們可以呼叫內建的$emit方法並傳入事件的名字,來向父級元件觸發乙個事件。例如:單擊按鈕,向父元件傳送『enlarge-text

』事件。

"

$emit('enlarge-text')

">enlarge text

3.1.2 通過函式第二個引數向父元件傳遞引數

"

$emit('enlarge-text', 0.1)

">enlarge text

然後當在父級元件監聽這個事件的時候,我們可以通過$event訪問到被丟擲的這個值:

post

...v-on:enlarge-text="

postfontsize += $event

">

解釋二:

通過第二小節可以將父元件的資料傳遞到子元件中。現在想讓父元件接受子元件的資料如何做的呢?通過發布訂閱模式。主要函式 $emit 丟擲乙個事件

例子:單擊子元件刪除對應的子元件。

3.2.1 繫結子元件單擊事件,並向父元件丟擲事件和資料。

vue.component('

list-item',}

",props:[

'content

','index'],

methods:

}});

當單擊子元件時,繫結的是handleclick 方法,首先在子元件中使用該方法處理。處理函式通過 $emit 方法丟擲 delete 事件(自定義事件) 和 index 資料。

3.2.2 父元件中監聽子元件的自定義的 delete 事件,並繫結處理函式。

item

v-for="

(item, index) of listitems

":key="

index

" :content="

item

":index="

index

"@delete="

handledelete

" >

當父元件監聽到子元件的 delete 事件後,使用 handledelete 方法進行處理:刪除對應元件。即將 listitems 中的對應資料刪除掉,頁面上就會對應刪除。

new

vue(,

methods: ,

handledelete: function (index) }})

完整**如下:

"en

">"

root

">

"inputvalue

">

"additem

">新增

view code

掌握vue核心概念之元件

推薦駝峰命名 或者 使用 還是看個人看法習慣 const globalcomponent template 這是乙個全域性元件 const localcomponent template 這是乙個區域性元件 vue.component globalcomponent globalcomponent ...

vue中的元件

2019年8月17日 使用vue.extend來建立全域性的vue元件 使用vue.extend來建立全域性的vue元件 var com1 vue.extend 使用vue.component 元件的名稱 建立出來的元件模板物件 如果使用vue component定義全域性元件的時候,元件名稱使用了...

Vue中父子元件通訊 元件todolist

提交 button div ul li v for item,index of list key index li ul div script newvue methods script view code 定義元件,元件和元件之間通訊 div id root div input type text...