directory

The VUE component has three elements

  1. Props parameters
  2. Slot Custom slot
  3. Event Indicates a user-defined event

Basic usage

In vue-CLI projects, component creation is very easy. Just create a new.vue file and write the HTML code in the template. A simple component is a complete component. Script and style

<template>
  <div class="headComponent"> Subcomponent {{{myData}} </div> </template> <script>export default {
    props:['data'.'type'],
    inheritAttrs: false.data() {return{
            myData:' ',}},mounted(){

    },
    methods:{
       
    }
}
</script>
<style scoped>

</style>
Copy the code

Then import and register the component in the js of another file to use it directly

import list from '.. /components/headComponent.vue'
Copy the code

Props: The parent component is passed to the child component

If a parent passes a parameter to its child, it needs props.

props:['data'.'type']
Copy the code

However, the application scenarios of common components are complex. Therefore, some verification rules should be added to the parameters passed by props in the following format:

Props: {// Basic type detection (' null 'means any type can be used) propA: Number, // multiple types propB: [String, Number], // Required and is a String propC: {type: String,
      required: true}, // numbers, with default values propD: {type: Number, default: 100}, // Array/object default values should be returned by a factory function propE: {type: Object,
      default: function () {
        return { message: 'hello'} // propF: {validator:function (value) {
        return value > 10
      }
    }
  }
Copy the code

// Vue2.5 has been optimized for props. This problem is resolved. If you need to do this, you can write: // Vue2.5 is optimized for props.

let copyData = JSON.parse(JSON.stringify(this.data))
Copy the code

Why not just say let myData = this.data? Because the assignment is direct, it’s just a shallow copy of the object and the array, pointing to the same memory address, and changing one of them changes the other. However, after the reverse conversion of JSON, the deep copy is realized, which can not affect each other.

The child component fires the parent component event

In a general-purpose component, there is usually a need for various events, such as a change event for a check box or a click event for a button in the component, and sometimes a child component needs to fire an event and pass it to the parent component

HandleSubmit (data){this: handleSubmit(data){this.$emit('submitToParent', data)
}
Copy the code
// Parent calls child <child-component @submittoparent ="parentSubmit"></child-component> ... . ParentSubmit (data){// parentSubmit(data){Copy the code

The logic in the parent component is processed by the parent component, and the logic made by the child component based on the parent component is processed by the child component. This not only reduces the coupling, but also ensures that the respective data is not contaminated.

Remember to leave a slot

A generic component can not perfectly adapt to all application scenarios, so when encapsulating the component, only 80% of the functions of the component need to be completed, and the remaining 20% need to be solved by the parent component through Solt

The above is a generic component, and in some scenarios, the buttons on the right are “handle” and “delegate.” In other scenarios, the button needs to be changed to “view” or “delete”. When encapsulating the component, you don’t need to write the button, you just need to leave a slot in place, place the button, and write the button in the parent component

Child component <div class="child-btn"> <! -- named slot --> <slot name="button"></slot> <! -- anonymous slot (only one per component) --> <slot><slot> </div> Parent <child> <! -- <button slot="button"> Slot button </button> </child>Copy the code

When developing generic components, it is recommended to reserve a slot for components that are not highly independent, even if you don’t know what to use it for.

Here’s another example:

During development, when new content is often added to a child component, one or more sockets can be left inside the child component

The subcomponent is then added when it is called

The added content is then distributed to the corresponding slot

Slot can also be used as a scope to define variables in a child component and then customize the way the child component is rendered in the parent:

In this example, we first add slot to the child component and define the array variable navS in the child component and then add content to the parent component in the scope template, where scope is the inherent property, Its value corresponds to a temporary variable, props, which receives the parameter navS passed from the parent to the child

The use of slot can also be found at juejin.cn/post/684490…

Vuex: Use it wisely but don’t abuse it

Child components pass data to child components

Vue does not have a method to pass parameters directly from child to child. It is recommended to combine all child components that need to pass data into one component. If you must pass parameters from child to child, you can pass them first from parent to child. Parent and child components transfer parameters through props and custom events. Non-parent and child components usually transfer parameters through Vuex. Vuex is designed to manage component state and can also be used for parameter transfer of complex components

But Vuex is not recommended, although it can be used to pass the reference. Because Vuex is similar to a global variable, it will always occupy memory. When writing large data states, it will cause memory leakage (people are alive, we can’t stop using things just because they have disadvantages, just use them properly). Tips: When the page is refreshed, Vuex will initialize and the edited data will be lost. If you need to keep the data while refreshing the page, you can save the ID through url or sessionStorage and ajax request the data

Component CSS: Use scoped to control style scope

When you write a component, you can add scoped to the style tag so that the styles in the tag only apply to the current component. However, using scoped is a sure way to create a lot of duplicate code. Therefore, you should avoid writing styles in the component. Add component styles via the scoped property

Dynamic components

Vue can also mount multiple sub-components in the same location, using variables to switch components, such as TAB menus

Recursive components

When a component has a name attribute, it can recursively call itself within its template, which is useful when developing tree components

Final render result:

Other situations

The child component changes the parent component’s data

In vue2.0, children are not allowed to change the parent’s data directly. In vue 1.0, this is possible, but often project requirements require changing the parent’s data. How can we do this? When we pass the parent element’s data to a child component, we pass a non-basic type, namely an object or array. The child component manipulates the data by accessing properties in the object. Since objects and arrays are referenced, the parent component changes the data synchronously, as follows:

// The parent component wants to props to pass data to the child component myData:{info:'Parent information'} // Subcomponent <template id="tpl">
    <div>
        <button @click="change">change</button> <p>{{data.info}}</p> </div> </template> ... Omit some irrelevant code... props:['data'],
methods:{
    change(){
        this.data.info = 'change info'}}Copy the code

When a child component clicks the change button to change data, the parent component also changes data synchronously

If you don’t want to influence the value of the parent component, we can also use the article beginning JSON reverse transformation way, in the mounted method for deep copy, initialize the data in the data on another variable as the bearing, bearing variable change, such ability won’t affect the value of the variable in the parent component.

Refer to the blog: www.cnblogs.com/wisewrong/p… www.cnblogs.com/yesyes/p/66…