Vue2 元件封裝
1.前言:
接觸一個前端架構,除了基礎的使用文法以外我們接下來都會很關心元件和複用的問題。以下就是個簡單的例子。
2. 子元件引入
下面是在父元件中引入子元件的代碼片段:
<template>
<div class="booklist_out_container">
<div class="booklist_container">
<BookItem v-for="book in books" :book="book"/>
</div>
<br/>
<button type="button" @click='onAddBook()' >add book</button>
</div>
</template>
<script>
import BookItem from '@/components/BookItem';
export default {
mounted() {
},
methods: {
onAddBook:function(){
this.books = [...this.books,`book${this.books.length}`];
}
},
name: "BookList",
data() {
return {
books:["book0","book1"],
msg: 'this is BookList',
};
},
components:{
"BookItem":BookItem
}
};
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.booklist_out_container{
width:500px;
height:400px;
margin: 0 auto;
}
.booklist_container {
width: 500px;
height: 300px;
border: 1px solid;
overflow-y:scroll;
}
</style>
從上面的例子可以看出,BookItem既是一個子元件,我們使用:
- import BookItem from ‘@/components/BookItem’; 方式将子元件引入父元件中。
- 使用 componets屬性,将BookItem元件注冊進父元件。
- 在template标簽中使用BookItem子元件。
3. 父元件->子元件傳值
使用上面的例子,我們可以看見 :book即是父元件注入到子元件中的一個值,
父元件片段:
<div class="booklist_container">
<BookItem v-for="book in books" :book="book"/>
</div>
子元件代碼:
<template>
<div class="bookitem_container">
{{book}}<button @click="signUp()">sign up</button>
</div>
</template>
<script>
export default {
props:{
book:String,
required:true
},
methods:{
signUp:function(){
alert(this.book);
}
},
mounted() {
},
name: "BookList",
data() {
return {
msg: 'this is BookList',
};
},
};
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.bookitem_container {
width:100%;
}
</style>
我們可以看見,子元件通過如下方式引入父元件傳入的值:
- 在 props中注冊這個值
props:{
book:String,
required:true
},
- 在模闆中使用:
<template>
<div class="bookitem_container">
{{book}}<button @click="signUp()">sign up</button>
</div>
</template>
- 在方法中調用:
methods:{
signUp:function(){
alert(this.book);
}
},
4.子元件向父元件傳值:
事實上vue2去掉了props的雙向綁定,表明了和react一樣希望資料流單純可控,但是實際上我們還是會需要和父元件進行通訊,我們使用$emit方式盡量解耦,方法如下:
将上面的父元件代碼修改一下,加入事件監聽代碼:
<template>
<div class="booklist_out_container">
<div class="booklist_container">
<BookItem v-for="book in books" :book="book" @:signupEvent="signUpEventListener"/>
</div>
<br/>
<button type="button" @click='onAddBook()' >add book</button>
</div>
</template>
可以看見關鍵的代碼是:
- @: 表示監聽子產品。
- signupEvent 表示監聽的事件。
- signUpEventListener 表示事件處理函數。
子元件增加發送事件代碼:
methods:{
signUp:function(){
this.$emit("signupEvent",`something value ${this.book}`);
}
},
- this.$emit 表示發送消息。
- signupEvent 表示發送一個自定義事件"signupEvent"。
-
表示發送的一個參數。something value ${this.book}
5.後記
至此,vue2的子產品封裝相關基礎知識已經講完,進階技巧可以參考官網文檔