vue-06 componentization practice

vue component practice

Component Foundation

A component is a reusable Vue instance with a name. We can use this component as a user-defined element in a Vue root instance created through new Vue.

Component registration, use and data transfer
Vue.component(name, options) can be used to register components.
Example: extract new course components and course list components

<!-- Custom components --> 
<course-list :courses="courses"></course-list>

<script>
    // Register the course list component 
    Vue.component('course-list', { 
        data() { 
            return { 
                // The changed status belongs to the internal status of course list, so it is used as data 
                selectedCourse: '', 
            }
        },
        props: { 
            // courses should also be accessed when adding a course, so it is passed as an attribute
            courses: { 
                type: Array, 
                default: [] 
            }, 
        },
        template: ` 
<div>
<!-- conditional rendering  --> 
<p v-if="courses.length == 0">No course information</p>
<!-- List rendering --> 
<ul>
<!-- class binding --> 
<li v-for="c in courses" :class="{active: (selectedCourse === c)}" @click="selectedCourse = c">{{c}}</li> <!-- style binding --> 
<!-- <li v-for="c in courses" :style="{backgroundColor: (selectedCourse === c)?'#ddd':'transparent'}" @click="selectedCourse = c">{{c}}</li> -->
    </ul>
    </div> `, 
    })
    const app = new Vue({ 
        el: '#app', 
        data: { 
            title: 'Class, shopping cart' 
        } 
    }) 

</script>

Component Foundation

Custom events and their listeners
When the child component needs to communicate with the parent component, it can dispatch and listen to user-defined events.
Example: add a course component and send a new event

<!-- Listen for component events --> 
<course-add @add-course="addCourse"></course-add> 
<script>
    // Component registration 
    Vue.component('course-add', { 
        data() { 
            return { 
                course: '', 
                // Extract course from parent component to course add maintenance 
            } 
        },template: `
<div>
<!-- Form input binding --> 
<input v-model="course" @keydown.enter="addCourse"/> 
<!-- event processing  --> 
<button v-on:click="addCourse">New courses</button> </div> `,
        methods: { 
            addCourse() { 
                // Send custom event notification to parent component 
                // Note that there should be no uppercase letters when defining the event name 
                this.$emit('add-course', this.course) this.course = '' 
            } 
        }, 
    })
    
    const app = new Vue({ 
        methods: { 
            // The callback function receives event parameters 
            addCourse(course) { 
                this.courses.push(course);
            } 
        },
    } 
</script>

Using v-model on components
Component implementation v-model
Example: transform course add to a version that supports v-model

<!-- Custom component support v-model Need to implement internal input of:value and@input -->
<course-add v-model="course" @add-course="addCourse"></course-add>
<script>
    Vue.component('course-add', {
        // Receive the value passed by the parent component without additional maintenance of course 
        props: ['value'], 
        template: ` <div><!-- Need to implement input of:value and@input --> <input :value="value" @input="onInput" @keydown.enter="addCourse"/> <button v-on:click="addCourse">New courses</button> </div> `,
        methods: { 
            addCourse() { 
                // Data transfer is no longer required for dispatch events 
                this.$emit('add-course') 
                // this.course = '' 
            },
            onInput(e) { 
                this.$emit('input', e.target.value)
            } 
        }, 
    })
    
    const app = new Vue({ 
        data: { 
            course: '', 
            // Restore course 
        },
        methods: { 
            addCourse() {
                // Restore addCourse 
                this.courses.push(this.course); this.course = ''; 
            } 
        } 
    }) 
</script>

The default conversion of v-model is: value and @ input. If you want to modify this behavior, you can define the model option

Vue.component('course-add', { 
    model: { 
        prop: 'value', 
        event: 'change' 
    } 
})

Distribute content through slots
You can pass content to components by using the elements provided by vue
Example: pop up window assembly

<style> 
    .message-box { 
        padding: 10px 20px; 
        background: #4fc08d; 
        border: 1px solid #42b983; 
    }
    .message-box-close { 
        float: right; 
    } 
</style> 
<!-- Slot for content distribution --> 
<message :show.sync="show">New course succeeded!</message>
<script> 
    // slot as placeholder 
    Vue.component('message', { 
        props: ['show'], 
        template: `
<div class="message-box" v-if="show"> 
<slot></slot> 
<span class="message-box-close" @click="$emit('update:show', false)">X</span>
</div> ` 
    })
    
    const app = new Vue({ 
        data: { 
            show: false, 
            // Prompt box status 
        },
        methods: { 
            addCourse() {
                // Prompt for new information 
                this.show = true; 
            } 
        }, 
    } 
</script>

If there are multiple independent content to distribute, you can use the named slot v-slot:name
Example: add a title section

<message :show.sync="show"> 
    <template v-slot:title>congratulations</template> 
    <template>New course succeeded!</template> 
</message>
Vue.component('message', { 
    props: ['show'], 
    template: ` <div class="message-box" v-if="show"> <strong><slot name="title"></slot></strong> <slot></slot> </div> ` 
})

slot

Understanding of Vue componentization
Componentization is the essence of Vue, and Vue applications are composed of components. Vue componentization involves a lot of content. During the interview, I was asked to talk about your understanding of Vue componentization. At this time, there may be no way to start, which can be explained from the following points:

Definition: components are reusable Vue instances. Specifically, they are instances of VueComponent and inherit from Vue.

Advantages: as can be seen from the above case, componentization can increase the reusability, maintainability and testability of code.
Usage scenario: when to use components? The following classifications can be used as a reference:

General components: realize the most basic functions and have universality and reusability, such as button components, input box components, layout components, etc.
Business components: they complete specific businesses and have certain reusability, such as login components and rotation chart components.
Page component: organize the independent content of each part of the application, and switch between different page components when necessary, such as list page and detail page components

How to use components

Definition: Vue.component(), components option, sfc (single file component)

Classification: stateful component, functional, abstract

Communication: props, $emit()/$on(), provide/inject, $children/$parent/$root/$attrs/$listeners

Content distribution:, v-slot

Usage and Optimization: is, keep alive, asynchronous component

Nature of components

Components in vue go through the following process

Component configuration = > vuecomponent instance = > render() = > virtual DOM = > DOM

So the essence of components is to generate virtual DOM

Keywords: Vue

Added by igorlopez on Sun, 07 Nov 2021 03:38:56 +0200