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"
- @: 表示监听模块。
- signupEvent 表示监听的事件。
- signUpEventListener 表示事件处理函数。
子组件增加发送事件代码:
methods:{
signUp:function(){
this.$emit("signupEvent",`something value ${this.book}`);
}
},
- this.$emit 表示发送消息。
- signupEvent 表示发送一个自定义事件"signupEvent"。
something value ${this.book}
表示发送的一个参数。
5.后记
至此,vue2的模块封装相关基础知识已经讲完,高级技巧可以参考官网文档