Vue realizes the encapsulation of public template components, data transfer, method execution, etc., and realizes custom modification of public template components (slot encapsulation)

Public template component encapsulation purpose

Through the public template component encapsulation, the code reuse of the public part of the business can be realized, unnecessary repeated development can be reduced, the development work can be lightened, and the embarrassment of repeated wheel creation can be avoided.

insert image description here

Technical points required for packaging

  • props: A one-way downward binding data flow and data validation are formed between parent and child props.
  • $emit: The method that triggers the parent component.
  • slot: The element acts as a content distribution slot in the component template. The slot element itself will be replaced.
  • Global registration of public template components: the prerequisite for the use of public template components.

Alternative upgrade technology points

  • watch: Listen to the data passed into the announcement template component.
  • ref: the method that executes the public template component

Public Template Component Encapsulation

1. Public template component encapsulation

<template>
    <div class="tzc_group_bt">
        <slot name="content" >
            <div class="tzc_group_header">
                <i :class="myvalue.icon" :style="{'color':myvalue.color}"></i>
                <p :style="{'color':myvalue.color2,'border-bottom':`2px solid ${myvalue.color}`}">{
    
    {
    
     myvalue.name }}</p>
            </div>
            <div class="tzc_group_more" @click="OnS()" :style="{'color':myvalue.color3,'background':myvalue.color}">{
    
    {
    
    myvalue.more}}</div>
        </slot>
    </div>
</template>

<script>
export default {
    
    
    props: {
    
    
        myvalue: {
    
    
            default: {
    
    }
        },
    },
    data() {
    
    
        return {
    
    

        };
    },
    mounted() {
    
    

    },
    methods: {
    
    
        OnS() {
    
    
            this.$emit('onOpen');
        }
    },
};
</script>

2. Global registration of public template components (main.js or main.ts)

//通过Vue.component进行全局注册
Vue.component('my-component-name', {
    
    
  // ... 选项 ...
})

3. Use of public template components

<cp_pub_more :myvalue="myvalue" @onOpen="onGlist" >
     <!-- 插入自定义内容插槽,传值、方法失效 -->
     <template v-slot:content>
         <div>插入自定义内容</div>
     </template>
 </cp_pub_more>

This article is original, and it is not easy to be original. If you need to reprint, please contact the author for authorization.

Guess you like

Origin blog.csdn.net/qq_36034945/article/details/129040932