vue component encapsulation and parent-child component value passing, event handling

In the development of vue, the part with unified function is extracted as an independent component and introduced when it is needed, which can effectively reduce code redundancy
The difficulty lies in how to encapsulate, use, transfer parameters, distribute events, etc. I will use flashback to explain
(this paper is summarized in the book of Vue2 practical decryption)
The code is as follows:
Package component BookList.vue

<template>
    <div class="book-list">
        <div class="header">
            <div class="heading">{{heading}}</div>
            <div class="more">More...</div>
        </div>
        <div class="book-items">
            <div class="book" v-for="book in books">
                <div class="cover">
                    <img :src="book.imgUrl" />
                </div>
                <div>{{book.title}}</div>
                <div>{{book.authors | join}}</div>
            </div>
        </div>
    </div>
</template>
<script>
    export default{
         props:['heading','books'],
         filters:{
             join(args){
                 return args.join(',');
             }
         }   
    }
</script>
You can't use data as a data container to input data to a component. Because data is an internal object, you need to replace it with props
 We can understand as follows:
    The scope of data is only applicable to the internal, but not visible to the external. props is a public component member variable that can be seen from the internal and external

The code of the Home.vue component is as follows:

<template>
    <div class="section">
        <book-list :books="books1" heading="Book list 1"></book-list>
    </div>
    <div class="section">
        <book-list :books="books2" heading="Book list 2"></book-list>
    </div>
</template>
<script>
    import BookList from './components/BookList.vue'
    export default{
         data(){
             return{
                 books1:[],
                 books2:[],
             }
        },
        components:{        //Register custom components
            BookList
        }
</script>

Tags: Javascript Vue

Posted on Wed, 04 Dec 2019 01:45:14 -0500 by mtimdog