This section describes component value transmission

Vue as one of the mainstream front-end frameworks, components have always been the core part of VUE. At first, I contacted the component in the process of learning vue between the value of the function, but because in the work with less, for this part no in-depth understanding, lead to some problems encountered in the process of development, through further study, I learned the vue components in the way of the value and the presence of two different types of components: by value Values passed between sibling components and between parent and child components

1. Functions of components

Component function: used to reduce the amount of code in the Vue instance (object), in the process of using the Vue development in the future, can according to the different business functions will be divided into different components in the page, then multiple components to build the entire page layout, convenient for using the Vue for development in the future when the page management (can reuse components), convenient maintenance in the future.

2. Component definition

2.1 Registering global components

A global component is registered with a Vue instance object and defined to be used within the scope of the Vue instance

<div id="app"> <! <h2>{{title}}</h2> <! - use global registration components, can reuse - > < login > < / login > < login > < / login > < / div > <! -- 1. Introduce framework support first (VUE file), recommended location before the body end tag (using the browser runtime, if using NodeJS is another way to introduce) --> <script SRC = "https://cdn.jsdelivr.net/npm/vue/dist/vue.js" > < / script > < script > / / define global component Vue.com ponent (' login '{ Template :'<diu><h2> User login page </h2></diu>'}); Let vm = new Vue({el: '#app', data: {title: 'component learning - global component registration'}}); </script>Copy the code

Code description:

  1. Vue.com Ponent is used to develop global components
  • Parameter 1: Defines the component name login
  • Parameter 2: component configuration {} template: “” is used to write the HTML code for the component. Only one root element must exist in the template
  1. Use global components by component name within the scope of the Vue instance
  2. If used in the process of registering a component, the hump naming rule is the way of the component. When using the component, all the words in the hump must be lowercase with a hyphen (-). Personally, the hump is not recommended.

2.2 Registering partial Components

Local component registration completes component registration by registering the component with a Components property in the corresponding Vue instance. This does not accumulate the Vue instance.

<div id="app"> <! <h2>{{title}}</h2> <login></login> </login> </register> </register> </register> <user-table></user-table> </div> <! - the third way - > < template id = "userTemplate" > < diu > < h2 > user list page < / h2 > < / diu > < / template > <! -- 1. Introduce framework support first (VUE file), recommended location before the body end tag (using the browser runtime, if using NodeJS is another way to introduce) --> <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> <! --> <script> let reg = {template: "<diu><h2> </diu>",}; const userTemplate = { template: "#userTemplate", }; Let vm = new Vue({el: "#app", data: {title: "component learning - component registration ",}, components: {login: {// "<diu><h2> </diu>", </h2></diu>",}, register: reg, // UserTemplate, // The third method: note that I use the camel, scaffold recommended method},}); </script>Copy the code

3. I will add the execution process of the parent-child component life cycle in the future

  • BeforeCreate: The component starts initialization, registering only its own events and lifecycle functions

  • Created: Data /methods/computed data methods have been injected to the component

  • BeforeMount: Compiles the Vue template pointing to HTML before rendering the content in the template

  • Mounted: Renders the COMPILED HTML template in the template to form a virtual DOM, replacing the template with the DOM

  • BeforeUpdate: When data changes in components, the beforeUpdate is triggered. The data on the page is still the original data

  • Updated: Indicates that the data on the page is consistent with the data attribute

  • BeforeDestroy: Triggers the method before destroying the VUE instance

  • Destroy: The VUE instance has been completely destroyed and the listening base has all disappeared

4. Component data transfer

4.1 (VuE3 following components delivered)

4.1.1 Parent –> Child (Prop)

The props function is used to pass static or dynamic data to a component

Props :[MSG]. MSG can be an object or a basic data type

4.1.1.1 Parent Component Content

<div >< div class="parent"> </Children: MSG ="message"></Children> </div> </template> <script  import Children from ".. /components/Children"; export default { name: "Parent", components: { Children, }, data() { return { message: "hello world", }; }}; </script>Copy the code

4.1.1.2 Sub-component content

{{myMsg}}</section> </template> <script> export default {name: "Children", components: Props: [" props "], data() {return {myMsg: this.msg,}; }, methods: {}, }; </script>Copy the code

4.1.2 Child -> Parent (emit)

$emit(‘ myEvent ‘) emits a custom event in the child component, then @myevent listens in the parent component

4.1.2.1 subcomponents

<div @click="clickme"> </div> </section> </template> <script> export default { name: "Children", components: {}, data() { return { childNum: 0, }; }, methods: {clickme() {$emit("addNum", this.childnum+ +); $emit("addNum", this.childnum+ +); ,}}}; </script>Copy the code

4.1.2.2 parent component

<template> <div class="parent"> $emit("addNum", this.childnum+ +); // emit("addNum", this.childnum+ +); // emit("addNum", this.childnum+ +); <Children-Com @addNum="getNum"></Children-Com> </div> </template> <script> import ChildrenCom from ".. /components/Children"; export default { name: "Parent", components: { ChildrenCom, }, data() { return { parentNum: 0, }; }, methods: {// childNum is passed by the child component. GetNum (childNum) {this.parentNum = childNum; ,}}}; </script>Copy the code

4.1.3 Sibling Component Transmission (Connected by a third-party declaration bus component)

Using the ability to trigger and listen for custom events, we define a common event bus, evenBus, which acts as an intermediate bridge to pass values to any component. By using eventBus, we can deepen the emit triggering and listening capabilities, and define a public event eventBus, which can act as a bridge between the emit and any component. And through the use of eventBus, we can deepen the understanding of Emit

4.1.3.1 bus components

    import Vue from 'vue' 
    export default new Vue()
Copy the code

4.1.3.2 Children1. Vue (first brother Component)

<template> <section> <div @click="Children1"> Push message</div> <br /> </section> </template> <script eventBus from "./EventBus"; export default { name: "Children1", components: {}, data() { return { childNum: 0, }; $emit("Children1", this.childnum+ +);}, methods: {Children1() {// emit the message eventbus. $emit("Children1", this.childnum+ +); ,}}}; </script>Copy the code

2. Vue (Second brother Component)

<template> <section>children1: {{MSG}}</section> </template> <script> import eventBus from "./ eventBus "; export default { name: "Children2", components: {}, data() { return { msg: "", }; $on("Children1", (children1Msg) => {this.msg = children1Msg; }); }}; </script>Copy the code

4.1.3.4 Put Children1 and Children2 into one component

<template> <div class="parent"> <Children1></Children1> </Children2> </Children2> </div> </template> <script> // introduce two sibling components Path component change import Children1 from ".. /components/Children1"; import Children2 from ".. /components/Children2"; export default { name: "Parent", components: { Children1, Children2, }, data() { return {}; }, methods: {}, }; </script>Copy the code

4.1.4 Transmitting values between routes

$router.push(‘ /B? Name = danseek ‘)

$route.query.name = this.$route.query.name = this

The routes are configured as follows

{path: '/b/:name', name: 'b', component: () => import('.. /views/B.vue') }Copy the code

4.2 (Components above vue3 pass values)

4.2.1 Props

4.2.1.1 the parent component

<template> <div class="home"> <div> <Children :data="num" @fatherNums="shouFun"></Children> </div> </div> </template> <script> import { ref } from "vue"; import Children from ".. /components/children"; Export default {name: "Home", components: {Children,}, setup(props) {// const num = ref(18); return { num, }; }}; </script>Copy the code

4.2.1.2 subcomponents

<template> <div> {{num}} </div> </template> <script> import {ref} from "vue"; Export default {props: {data: Number,}, setup(props, {emit}) {// props const num = ref(props. Data); return { num, }; }}; </script>Copy the code

4.2.2 Sending Messages from children to Parents (Emit)

4.2.2.1 the parent component

<template> <div class="home"> <div> <p>{{nums}}</p> <Children :data="num" @fatherNums="shouFun"></Children> </div> </div> </template> <script> import { ref } from "vue"; Import Children from ".. /components/children"; Export default {name: "Home", // is a component that is imported via the Components attribute: { Children, }, setup(props) { const nums = ref(null); Const shouFun = (val) => {console.log(val); nums.value = val; }; return { nums, }; }}; </script>Copy the code

4.2.2.2 subcomponents

<template> <div> < button@click ="fatherNum"> </button> </div> </template> <script> import {ref} from "@vue/reactivity"; export default { props: { data: Number,}, setup(props, {emit}) {// emit(props, {emit}) const fatherNum = () => {emit("fatherNums", 666); }; return { fatherNum, }; }}; </script>Copy the code

conclusion

Component delivery benefits

The advantages of sending props data are obvious, flexible and simple. You can perform data calculation, data listening, and other processing on props data, which is very flexible and convenient, but only the parent and child layer here.

Component delivery disadvantages

When we use the props of the parent component in a child component, the props are somehow modified, and the data of the parent component is also tampered with. This makes us wonder, isn’t it true that the props of the parent component cannot be modified? How has this changed,

Actually, can props in Vue change this scoring situation?

Props if it is the underlying data type, it will throw an error when changed:

When props is a reference type, we can change the truth of one of the properties of the data.

If the parent component is a reference type, the child component can modify the properties under prop of the parent component. If the parent component is a reference type, the child component can modify the properties under prop of the parent component.

This is embarrassing. This is acceptable if we design it so that the parent data can be changed at the same time. If we don’t want the parent data to change, this is a serious logic bug. That’s one of the risks of Props communications.