First, Vue foundation

First, template syntax

1.1 Data Binding

1.1.1 Text, V-text, {{}}

In mustache you can use the addition, subtraction, multiplication and division operators

	<div id="app">
		<div>
			{{uage *2}}
		</div>
		<div v-text="uage"></div>
	</div>
Copy the code
<script>
	const app = new Vue({
		el:'#app'.data: {uage:10
		}
	})
</script>
Copy the code

1.1.2 v – once:

Bind values only once

	<div id="app">
		<div v-once>
			{{uage}}
		</div>
	</div>
Copy the code

1.1.3 v – pre:

Render the contents of the tag without compiling

	<div id="app">
		<div v-pre>
			{{uage *2}}
		</div>
	</div>
Copy the code

1.1.4 v – cloak:

Render the page after the data is loaded

	<div id="app">
		<div v-cloak>
			{{uage *2}}
		</div>
	</div>
Copy the code

The V-cloak attribute prevents the element from being displayed until the data is loaded, and the v-cloak attribute does not appear until the page is rendered

1.1.5 v – HTML

Insert characters with HTML

	<div id="app">
		<div v-html ='url'>
		</div>
	</div>
Copy the code
<script>
	const app = new Vue({
		el:'#app'.data: {uage:10.url:'<a href="http://www.baidu.com">ddd</a>'
		}
	})
</script>
Copy the code

1.1.6 v – bind:

Dynamically binding property values

Grammar sugar…

	<div id="app">
		<a v-bind:href= "url">I am the baidu</a>
	</div>
Copy the code
<script>
	const app = new Vue({
		el: '#app'.data: {
			uage: 10.url: 'http://www.baidu.com'
		}
	})
</script>
Copy the code

The == extension uses: binding class==

The CSS file

		.active {
			color: red;
		}

		.uncheck {
			color: yellow;
		}
		.green{
			color: green;
		}
Copy the code

Js file

<script>
	const app = new Vue({
		el: '#app'.data: {
			isActive: true.isUncheck: false

		},
		methods: {
			btnClick: function () {
				this.isActive = !this.isActive,
					this.isUncheck = !this.isUncheck

			},
			getClass:function(){
				return  {active:this.isActive,uncheck:this.isUncheck}
			}
		}
	})
</script>
Copy the code

Usage 1: Bind a class directly with {}

		<div :class={active:true}>I'm a direct binding style</div>
Copy the code

Use a variable passing in a Boolean type to control whether multiple classes are valid

		<div @click="btnClick" :class="{active:isActive,uncheck:isUncheck}" >I'm going to change color</div>
Copy the code

Usage three: with other classes, in case of style conflicts to a separate class

		<div @click="btnClick" :class="{active:isActive,uncheck:isUncheck}"class="green" >I'm going to change color</div>
Copy the code

If it is too complicated, use methods or computed

		<div @click="btnClick" v-bind:class="getClass()"</div>// The method can be called without parentheses
Copy the code

Using the array binding class:

		<div :class= "['green','fontClass']" class="active" >I'm bound to several classes</div>
Copy the code

This method can use variables in data and does not conflict with classes written separately. However, when rendering, the inline class is rendered first, so if there is style overlap, the bound style will override the inline class.

  • V – bind binding style

    		<div :style="{fontSize:'30px'}">I bound style</div>
    		<div :style="{color:color,fontSize:fontSize+'px'}">I also bound style</div>
    Copy the code
    		data: {
    			color: "red".fontSize:30
    
    		},
    Copy the code

    Matters needing attention:

    1. Format for: style= "{attribute name: attribute value}"
    2. If the attribute value is similar to font size with-Attribute values must be converted to fontSize, otherwise an error is reported
    3. Property values are incremented if written directly' 'If it is a variable, do not add
        computed: {
            fullName:function(){
                return this.firstName + ' ' + this.lastName; }},Copy the code

1.1.7 v – model

To create a bidirectional binding on the form, the V-Model ignores the initial values of the value, Checked, and Selected attributes of all form elements and selects the Vue instance data as the concrete values.

<body>
    <div id="app">
        <input type="text" v-model = "userName">
        <p>{{userName}}</p>
    </div>

</body>
<script>
    const app = new Vue({
        el:"#app".data: {userName:"hong"}})</script>
Copy the code

Related uses of V-Model:

<body>
    <div id="app">
        <!-- v-model与radio的配合使用 -->

        <label for="male">
            <input id="male" type="radio" name="sex" v-model="sex" value="Male">male</label>
        <label for="female">
            <input id="female" type="radio" name="sex" v-model="sex" value="Female">female</label>
        <p>The selected gender is: {{sex}}</p>
        <! -- V-model with checkBox -->
        <! -- <input type="checkbox" value=" checked"> Basketball <input type="checkbox" value=" football "V-model ="checked"> football <input Type ="checkbox" value=" table tennis "V-model ="checked"> Table tennis <input type="checkbox" value=" badminton" V-model ="checked"> badminton <input Type ="checkbox" value=" checked"> <input type=" golf "value=" checked">
        <label v-for= "item in hobbies" :for="item" >
            <! Note that label for and input ID need to be dynamically bound, and input value need to be dynamically bound.
            <input type="checkbox" :value="item" :id="item" v-model= "checked" >{{item}}
        </label>
        <p>I checked {{checked}}</p>
        <! Select * from vmodel select * from vmodel
        <select  name="" id="" v-model= "checkBooks" multiple>
            <option v-for = "item in books" :value="item">{{item}}</option>
        </select>
        <p>I checked: {{checkBooks}}</p>
    </div>

</body>
<script src=".. /js/vue.js"></script>
<script>
    Vue.component('cpn', cpnC)
    const app = new Vue({
        el: '#app'.data: {
            // Give the checkbox a default value of "male"
            sex: 'male'./ / radio
            checked: []./ / multi-select
            hobbies: ["Football"."Table tennis"."Badminton"."Football"."Golf"].books: ["How is steel tempered?"."Ah"."How to learn Linux?"."The front end is so hard."."Study hard"].checkBooks: []}})</script>
Copy the code

1.1.7.1 model modifier

  1. .lazy

    By default, v-model is used to synchronize the values and data in the input box in real time. After lazy, it changes to change time and then synchronizes data.

    <input type="text" v-model.lazy = "userName">
    Copy the code
  2. .number

    Converts user input to numeric type using the same rules as js Number()

    See the JS data type conversion in W3shool

    <input type="text" v-model.number = "userName">
    Copy the code
  3. .trim

    Filter out the first space of the input box

    <input type="text" v-model.trim = "userName">
    Copy the code

1.2 Event Binding

1.2.1 v – on

Function: Binds event listeners

Grammar sugar: @

Parameters: the event

1.2.1.1 Basic Usage

Bind events using V-ON

  • Multiple different events can be bound to an element
  • Binding of events can also be done using methods that define functions
  • When defining an event with no parameters, we do not need to add () when calling a method.
<body>
    <div id="app">
        <p>{{total}}</p>
        <! Multiple different events can be bound to an element.
        <div class="div1" @mouseout = "total++" @click = "total--"></div>
        <! Events can also be bound using methods that define functions.
        <! Since the event defined now has no parameters, we do not need to add () when calling the method -->
        <button v-on:click = "reduce">-</button>
        <button v-on:click = "increase">+</button>
    </div>

</body>
<script>
    const app = new Vue({
        el:"#app".data: {total:1
        },
        methods: {// Define the function added by total
            increase(){
                this.total++;
            },
            // Define the total reduction function
            reduce(){
                this.total--; }}})</script>
Copy the code

1.2.1.2 Event Listening Parameter Transmission

  • When a method requires arguments but does not pass arguments, the event object is returned as the default argument
  • Normal transfer parameter
  • This is used when passing other parameters and events$eventimplementation
<body>
    <div id="app">
        <! The event event is returned as the default parameter.
        <button @click = "clickBtn">button</button>
        <! Pass the required parameters -->
        <button @click = "clickBtn1('sss')">button</button>
        <! $event (vUE); $event (vUE);
        <button @click = "clickBtn2(123,$event)">button</button>
        
    </div>

</body>
<script>
    const app = new Vue({
        el:"#app".data:{

        },
        methods: {clickBtn(){
                console.log(event);
            },
            clickBtn1(a){
                console.log(a);
            },
            clickBtn2(a,event){
                console.log(a,event); }}})</script>
Copy the code

1.2.2 V-ON modifier

  • .stop calls event. stopPropagation()
  • . Prevent call event. The preventDefault ()
  • . {keyCode | keyAlias} is the event to trigger only from a specific button activates the callback
  • Native listens for the native event of the component root element
  • .once Triggers only one callback
        <! -- Stop bubbling -->
        <button @click.stop = "clickBtn">button</button>
        <! -- Block default behavior -->
        <button @click.prevent = "clickBtn">button</button>
        <! -- Block default behavior, no expression -->
        <form @submit.prevent></form>
        <! -- concatenation modifier -->
        <button @click.stop.prevent = "clickBtn">button</button>
        <! -- Key alias, the name on the keyboard -->
        <input @keydown.+ = "onEnter">
        <! -- Key code, key corresponding code number -->
        <input @keydown.13 = "onEnter">
Copy the code

1.2.2 V-if, V-else, V-else -if

1.. 2.2.1 v – if, v – else

V-if is used in the same way as if in js. It is defined by v-if = “” Boolen value in quotes. If it is false, hide the element and display it as true

<body>
    <div id="app">
        <div v-if="isShow">true</div>
        <div v-else>false</div>
        <button @click="changeClick">switch</button>

    </div>

</body>
<script>
    const app = new Vue({
        el: "#app".data: {
            isShow: true
        },
        methods: {
            changeClick() {
                this.isShow = !this.isShow; }}})</script>
Copy the code

1.2.2.2 v – else – the if

Not much use, not superfluous

    <div id="app">
        <div v-if="score >90 ">good</div>
        <div v-else-if="score >80 ">good</div>
        <div v-else-if="score > 60">Pass the</div>
        <div v-else>Don't pass the</div>
    </div>
Copy the code

1.3 V-for loop traversal

Usage and for… In the same way, see w3school for… In introduction

1.3.1 Looping Arrays

1.3.1.1 No Index Loop

<body>
    <div id="app">
        <ul>
            <li v-for = "item in names" v-block>{{item}}</li>
        </ul>
    </div>

</body>
<script>
    const app = new Vue({
        el: "#app".data: {
            names: ["h"."w"."l"."g"."z"]},methods: {}})</script>
Copy the code

1.3.1.2 Index loops

  • I’m going to put a little bracket, and I’m going to put item and index
        <ul>
            <li v-for = "(item,index) in names" v-block>{{index}}----{{item}}</li>
        </ul>
Copy the code

1.3.2 Object Loop Iteration

1.3.2.1 Traversal Without Key and Without Index

<body>
    <div id="app">
        <ul>
            <li v-for = "item in names" v-block>{{item}}</li>
        </ul>
    </div>

</body>
<script>
    const app = new Vue({
        el: "#app".data: {
            names: {name:"hong".age:18.sex:"Male"}},methods: {}})</script>
Copy the code

1.3.2.2 Traversal with Key but Without Index

        <ul>
            <li v-for = "(item,key) in names" v-block>{{key}}------{{item}}</li>
        </ul>
Copy the code

1.3.2.2 Traversal with Key and Index

 <ul>
  <li v-for = "(item,key, index) in names" v-block>{{key}}------{{item}}-----{{index}}</li>
</ul>
Copy the code

1.4(Understanding) How to use key correctly

  1. When using V-for, we need to use the key attribute when using V-for for better reuse

    <body>
        <div id="app">
            <ul>
                <li v-for = "item in names" key = "item">{{item}}</li>
                <li v-for = "item in user" key = "item">{{item}}</li>
            </ul>
        </div>
    
    </body>
    <script>
        const app = new Vue({
            el: "#app".data: {
                names: {name:"hong".age:18.sex:"Male"
                },
                user: ["s"."d"."f"."j"]},methods: {}})</script>
    Copy the code

2. Calculate attributes

2.1 Basic Usage

    <div id="app">
        <div>{{fullName}}</div>
    </div>
Copy the code
        data: {
            firstName: 'zhang'.lastName: 'san'
        },
        computed: {
            fullName: function () {
                return this.firstName + ' ' + this.lastName; }},Copy the code

ES6 grammar

  1. Object enhanced syntax

    ES5 creation method

    var a = new Object(a); a.sname ="hong";
    Copy the code
    var a = {
        sname = "hong"
    }
    Copy the code
  2. ES6 grammar

    const sname =  "hong";
    var a = {
        sname,
    }
    // In es6 syntax, the above notation will treat sname as the key and assign the value of the variable sname to it
    Copy the code

Four, components,

4.1 Global components and Local Components

<body>
    <div id="app">
        <! -- Global components can be called anywhere -->
        <global-c></global-c>
        <! Local components can only be called within a registered component -->
        <cpn></cpn>
    </div>
    <div id="app2">
        <global-c></global-c>
        <! -- <cpn></cpn> -->
    </div>

</body>
<script src=".. /js/vue.js"></script>
<script>
    // Define the component
    const cpnC = Vue.extend({
        template: ` 
        
hhh
`
}) // Global component registration Vue.component('globalCi', cpnC) const app = new Vue({ el: '#app'.data: {},// Local component registration components: { cpn: cpnC } }) const app2 = new Vue({ el: "#app2",})
</script>
Copy the code

Tip: Component names allow hump, but when used, use uppercase letters followed by a hyphen –

Vue.com Ponent (‘globalComponent’,***) is required when used

4.2 Parent and Child Components

<body>
    <div id="app">
        <cpn></cpn>
    </div>
</body>
<script src=".. /js/vue.js"></script>
<script>// Define component 1 const cpnC = vue.extend ({template: '<div>I'm component 1</div>  
        `
    })
    const cpnC2 = Vue.extend({
        template: `
        <div>I'm component 2<! Call the registered component in the parent component -->
            <sonCpn></sonCpn>
        </div>', components:{// sonCpn:cpnC}}) const app = new Vue({el: '#app', data: {}, // Register component 2 in root component, use component Components: {CPN: cpnC2}}) const app2 = new Vue({el: "#app2",})</script>
Copy the code

When calling a component, the Vue object will first look in its own component to see if the component is registered. If not, it will look in the global component. If not, an error will be reported

4.2.1 Parent-child Component syntax sugar

The old way

    // Define the component
    const cpnC = Vue.extend({
        template: '
      
I'm component 1
}) // Global component registration Vue.component('globalCi', cpnC) Copy the code

The new writing

    Vue.component("ss", {template: '
      
I'm component 1
}) //------------------------------------------ components: { cpn: { template: '
I'm component 1
}}//----------------------------------------------- const cpn = { template: '
I'm component 1
} // Defined in the VUE component const app = new Vue({ el: '#app'.components: { //ES6 syntax, key and value are the same cpn } }) Copy the code

4.2.2 Remove the Template

4.2.2.1 Using the Script Label

Use tag to wrap THE HTML code, and assign an ID value, to achieve HTML code stripping

<body>
    <div id="app">
        <cpn></cpn>
        <cpn1></cpn1>
        <! -- <cpn2></cpn2> -->

    </div>
    <script type="text/x-template" id="test">
        <div>I am a component, but the code is removed oh ~</div>
    </script>


</body>
<script src=".. /js/vue.js"></script>

<script>
    // Here is how to register global components
    Vue.component('cpn', {
        template: "#test"
    })

    const app = new Vue({
        el: '#app'.// Here is how to register a local component
        components: {
            cpn1: {
                template: "#test"}}})</script>
Copy the code

4.2.2.2 Using the Template Label

Use the
tag to wrap the HTML code, and assign an ID value to achieve HTML code stripping

    <template id="test02">
        <div>Hi ~ I implemented this using the template tag</div>
    </template>
Copy the code

The implementation method is the same as above but the tag usage method is different

: Low_brightness: Notice that it is possible to use variables in the component but data uses the data(){} method, which returns an object == as follows

    // Here is how to register global components
    Vue.component('cpn1', {template:"#test02".// Data must use methods, and then return
        data(){
            return {
                title:"I am the title."}}})Copy the code

Because each call to the method ruturn generates objects ata different address, and changes are synchronized when reused, the designers specifically specified the way components must use data(){reutrn {}}

The same theory, to help understand

function a (){
    return {
        sname:"hong".sage:18}}let b = a();
let c = a();
let d = a();
// B, C,d above are not the same physical address
Copy the code

4.2.3 Value Transfer between Parent and Child Components

4.2.3.1 father the son
  • Pass the value through the props property

    <body>
        <div id="app">
            <cpn :cmovies="movies"></cpn>
        </div>
        <! Below is the HTML for the child component -->
        <template id="ccpn">
            <div>
                {{cmovies}}
            </div>
        </template>
    </body>
    <script src=".. /js/vue.js"></script>
    <script>
        // Here are the sub-components
        const cpn = {
            template: '#ccpn'.props: ['cmovies'].data() {
                return{}}}// The root component is also the parent component
        const App = new Vue({
            el: "#app".data() {
                return {
                    movies: ['the sea king'.'pirates']}},components: {
                cpn,
            }
    
        })
    </script>
    Copy the code

    Using the method above, we use the props attribute to pass data from the parent component to the child component, and the V-bind attribute to bind variables of the child component to variables in the parent component when calling the child component

    • compnentsAttributes can be used in more than one way[]You can also use{}When using object syntax, we can validate the data type passed to us. The basic syntax is as follows
4.2.3.1.1 Using the PORPS attribute
  • Dynamic props

    The code above is the dynamic props

  • Static props

    <body>
        <div id="app">
            <! -- props static assignment -->
            <cpn cmovies="sss"></cpn>
        </div>
        <template id="ccpn">
            <div>
                {{cmovies}}
            </div>
        </template>
    </body>
    Copy the code

    Note:

    • The props variable does not need to be added:, do not add:In this case, the subsequent assignment is not considered a variable
  • Props to verify

     props: { 
                        // Base type detection, null means any type can be used
                        propA: Number.// Multiple types
                        propB: [String.Number].// Mandatory and String
                        propC: {
                            type: String.required: true
                        },
                         // Numbers have default values
                        propD: {
                            type: Number.default: 101
                        },
                         // Array, the default value is a factory function return object
                        propE: {
                            type: Object.default: function () {
                                console.log("propE default invoked.");
                                return {
                                    message: "I am from propE."}; }},// Customize the validation function
                        propF: {
                            isValid: function (value) {
                                return value > 100; }}}Copy the code

    The types that can be detected are:

    • String
    • Number
    • Boolean
    • Function
    • Object
    • Array
    • Symbol

    Unidirectional data flow

    The props are bound unidirectionally: when properties of the parent component change, they are transmitted to the child component, but not vice versa. This is to prevent the child component from modifying the state of the parent component.

    Therefore, you should not change the values in props in child components, and Vue will warn you.

    let childNode = {
      template: ` < div class = "child" > < div > < span > child components data < / span > < input v - model = "forChildMsg" / > < / div > < p > {{forChildMsg}} < / p > < / div > `.props: {
        "for-child-msg": String}};let parentNode = {
      template: ` < div class = "parent" > < div > < span > parent component data < / span > < input v - model = "MSG" / > < / div > < p > {{MSG}} < / p > < the child :for-child-msg="msg">  `.components: {
        child: childNode
      },
      data() {
        return {
          msg: "default string."}; }};Copy the code

    Here we have an input box for both parent and child components and display parent and child data. When we enter new data in the parent’s input box, the synchronized child data is also modified; This is the function passing data to the subcomponents. When we modify the input field of the child component, the browser console reports an error warning

    [Vue warn]: Avoid mutating a prop directly since the value will be overwritten whenever the parent component re-renders. Instead, use a data or computed property based on the prop’s value. Prop being mutated: “forChildMsg”

  • Modifying props Data

    • There are usually two reasons:
    • When prop is passed in as an initial value, the child component wants to use it as local data
    • After prop is passed in as an initial value, it is processed into other data output by the child components

    Solutions:

    • Define a local variable and initialize it with the value of prop

    But because the ownChildMsg defined can only accept the initial value of forChildMsg, ownChildMsg cannot receive updates when the value to be passed by the parent component changes.

    let childNode = {
      template: 
            

    {{forChildMsg}}

    ownChildMsg : {{ownChildMsg}}

    `
    .props: { "for-child-msg": String }, data() { return { ownChildMsg: this.forChildMsg }; }};Copy the code

    Here we added one

    OwnChildMsg (default); ownChildMsg (default); ownChildMsg (default);

    • Define a calculation property that handles the value of prop and returns it

      Because it is a calculated property, values can only be displayed, not set. What we set up here is that once we modify the forChildMsg data from the parent component, we add a string “– ownChildMsg” to forChildMsg and display it on the screen. It is possible to update ownChildMsg data whenever the parent modifies new data.

      let childNode = {
        template: 
                

      {{forChildMsg}}

      ownChildMsg : {{ownChildMsg}}

      `
      .props: { "for-child-msg": String }, computed: { ownChildMsg() { return this.forChildMsg + "---ownChildMsg"; }}};Copy the code
    • A more appropriate approach is to use variables to store the initial value of a prop and watch to see how the prop value changes. Update the value of a variable when changes occur.

      let childNode = {
        template: 
                

      {{forChildMsg}}

      ownChildMsg : {{ownChildMsg}}

      `
      .props: { "for-child-msg": String }, data() { return { ownChildMsg: this.forChildMsg }; }, watch: { forChildMsg() { this.ownChildMsg = this.forChildMsg; }}};Copy the code
    • Unidirectional data flow

    The props are bound unidirectionally: when properties of the parent component change, they are transmitted to the child component, but not vice versa. This is to prevent the child component from modifying the state of the parent component.

    Therefore, you should not change the values in props in child components, and Vue will warn you.

    let childNode = {
      template: ` < div class = "child" > < div > < span > child components data < / span > < input v - model = "forChildMsg" / > < / div > < p > {{forChildMsg}} < / p > < / div > `.props: {
        "for-child-msg": String}};let parentNode = {
      template: ` < div class = "parent" > < div > < span > parent component data < / span > < input v - model = "MSG" / > < / div > < p > {{MSG}} < / p > < the child :for-child-msg="msg">  `.components: {
        child: childNode
      },
      data() {
        return {
          msg: "default string."}; }};Copy the code

    Here we have an input box for both parent and child components and display parent and child data. When we enter new data in the parent’s input box, the synchronized child data is also modified; This is the function passing data to the subcomponents. When we modify the input field of the child component, the browser console reports an error warning

    [Vue warn]: Avoid mutating a prop directly since the value will be overwritten whenever the parent component re-renders. Instead, use a data or computed property based on the prop’s value. Prop being mutated: “forChildMsg”

  • Modifying props Data

    There are usually two reasons:

    • When prop is passed in as an initial value, the child component wants to use it as local data

    • After prop is passed in as an initial value, it is processed into other data output by the child components

    The answer is

    • Define a local variable and initialize it with the value of prop

      But because the ownChildMsg defined can only accept the initial value of forChildMsg, ownChildMsg cannot receive updates when the value to be passed by the parent component changes.

      let childNode = {
          template: 
            

    {{forChildMsg}}

    ownChildMsg : {{ownChildMsg}}

    `
    .props: { "for-child-msg": String }, data() { return { ownChildMsg: this.forChildMsg }; }};Copy the code

    Here we added one

    OwnChildMsg (default); ownChildMsg (default); ownChildMsg (default);

    • Define a calculation property that handles the value of prop and returns it

      Because it is a calculated property, values can only be displayed, not set. What we set up here is that once we modify the forChildMsg data from the parent component, we add a string “– ownChildMsg” to forChildMsg and display it on the screen. It is possible to update ownChildMsg data whenever the parent modifies new data.

    let childNode = {
      template: 
            

    {{forChildMsg}}

    ownChildMsg : {{ownChildMsg}}

    `
    .props: { "for-child-msg": String }, computed: { ownChildMsg() { return this.forChildMsg + "---ownChildMsg"; }}};Copy the code
    • A more appropriate approach is to use variables to store the initial value of a prop and watch to see how the prop value changes. Update the value of a variable when changes occur.
    let childNode = {
      template: 
            

    {{forChildMsg}}

    ownChildMsg : {{ownChildMsg}}

    `
    .props: { "for-child-msg": String }, data() { return { ownChildMsg: this.forChildMsg }; }, watch: { forChildMsg() { this.ownChildMsg = this.forChildMsg; }}};Copy the code

    Part of the code above using www.jianshu.com/p/89bd18e44…

4.2.3.2 son father
  • Emit the event via $emit() in the child component.

  • Listen for child component events via V-on in the parent component

    <! DOCTYPEhtml>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="Width = device - width, initial - scale = 1.0">
        <title>Document</title>
    </head>
    <body>
        <! Parent component template -->
        <div id="app">
            <! If you omit an argument when calling childMessage, the system will automatically receive the value passed by the child component method.
            <cpn @btn-click = childMessage></cpn>
        </div>
        
    <! -- Subcomponent template -->
        <template id="cpn">
            <div>
                <button @click = "logClick(item)" v-for = "item in categories">{{item.wname}}</button>
            </div>
        </template>
    </body>
    <script src=".. /js/vue.js"></script>
    <script>
        / / child component
        const cpn ={
            template:"#cpn".data(){
                return {
                    categories:[
                        {
                            id:1.wname:'basketball'}, {id:2.wname:Table tennis
                        },
                        {
                            id:3.wname:'badminton'}}},],methods: {logClick(item){
                    // This output is done within the child component itself
                    console.log("I clicked.",item.wname);
                    // Pass the data to the parent
                    this.$emit('btn-click',item.wname,)
                }
            }
        }
        / / the parent component
        const app = new Vue({
            el:'#app'.data(){
                return{
                message:'hello'}},methods: {childMessage(arg){
                    console.log(arg); }},components:{
                cpn
            }
        })
    </script>
    </html>
    Copy the code

Parent-child group access

4.3.4.1 The Parent Accesses the Child
  • $children

    $children is an array, printed to display VueComponent, which contains a lot of data, including properties or methods from the component.

    • Overall code:
    <! DOCTYPEhtml>
    <html lang="en">
    
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="Width = device - width, initial - scale = 1.0">
        <title>Document</title>
        <script src=".. /js/vue.js" type="text/javascript"></script>
    </head>
    
    <body>
        <div id="app">
            <button @click="btnClick">button</button>
            <Cpn></Cpn>
        </div>
        <template id="cpn">
            <div>I'm a child component</div>
        </template>
    </body>
    
    <script>
        // Here are the sub-components
        const Cpn = {
            template: '#cpn'.// The child component's data must be in the form of a method
            data(){
                return{
                    msg:"I'm a message in a child component."}},methods: {
                showMessage() {
                    console.log("sss");
                    return  "I'm what's returned."}}};// Here is the parent component
        const app = new Vue({
            el: "#app".data() {
                return{}},methods: {
                btnClick() {
                    / / get $children
                    console.log(this.$children);
                    // Get the method in the child component and call
                    console.log(this.$children[0].showMessage());
                    // Get the variables in the child data
                    console.log(this.$children[0].msg)
                },
            },
            components: {
                Cpn
            }
        })
    </script>
    
    </html>
    Copy the code
    • Key code:
     methods: {
                btnClick() {
                    / / get $children
                    console.log(this.$children);
                    // Get the method in the child component and call
                    console.log(this.$children[0].showMessage());
                    // Get the variables in the child data
                    console.log(this.$children[0].msg)
                },
            },
    Copy the code

    However, this is not recommended because this method can be affected if the DOM tree changes later.

  • $refs

    Refs is an object, empty by default, that contains all the elements of the selected child component

    • Add attribute names via attribute ref on the subset you want to use

    • Use the $refs. property name at the parent level to get data from the component

    • The overall code

      <! DOCTYPEhtml>
      <html lang="en">
      
      <head>
          <meta charset="UTF-8">
          <meta name="viewport" content="Width = device - width, initial - scale = 1.0">
          <title>Document</title>
          <script src=".. /js/vue.js" type="text/javascript"></script>
      </head>
      
      <body>
          <div id="app">
              <button @click="btnClick">button</button>
              <Cpn ref="son" ></Cpn>
          </div>
          <template id="cpn">
              <div>I'm a child component</div>
          </template>
      </body>
      
      <script>
          const Cpn = {
              template: '#cpn'.// The child component's data must be in the form of a method
              data(){
                  return{
                      msg:"I'm a message in a child component."}},methods: {
                  showMessage() {
                      console.log("sss");
                      return  "I'm what's returned."}}};const app = new Vue({
              el: "#app".data() {
                  return{}},methods: {
                  btnClick() {
                      // // get $children
                      // console.log(this.$children);
                      // // gets the method in the child component and invokes it
                      // console.log(this.$children[0].showMessage());
                      // // gets variables in the child component data
                      // console.log(this.$children[0].msg)
      
                      / / print $refs
                      console.log(this.$refs);
                      // Get the MSG variable for AAA
                      console.log(this.$refs.son.msg);
                      // The method to get aaa
                      console.log(this.$refs.son.showMessage()); }},components: {
                  Cpn
              }
          })
      </script>
      
      </html>
      Copy the code
    • Key code;

          btnClick() {
              / / print $refs
              console.log(this.$refs);
              // Get the MSG variable for AAA
              console.log(this.$refs.son.msg);
              // The method to get aaa
              console.log(this.$refs.son.showMessage());
          },
      Copy the code
  • Child visits parent (understanding)

    • $parent

      You can access the direct parent of a child component (but for this reason, a component may have multiple parents during development, but not all of them will have the property you want, so undefined will be returned, so development is generally not used).

      • The complete code

        <! DOCTYPEhtml>
        <html lang="en">
        
        <head>
            <meta charset="UTF-8">
            <meta name="viewport" content="Width = device - width, initial - scale = 1.0">
            <title>Document</title>
            <script src=".. /js/vue.js" type="text/javascript"></script>
        </head>
        
        <body>
            <div id="app">
                <cpn ref="son"></cpn>
            </div>
            <! Here are the CPN subcomponents -->
            <template id="cpn">
                <div>
        
                    <div>I am a CPN component</div>
                    <ccpn></ccpn>
                </div>
        
        
        
            </template>
            <! Here is the CCPN component
            <template id="ccpn">
                <div>
                    <div>I am a CCPN component</div>
                    <button @click="checkParent">button</button>
                </div>
            </template>
        </body>
        
        <script>
            // Here are the children of CPN
            const ccpn = {
                template: "#ccpn".methods: {
                    checkParent() {
                        console.log(this.$parent.msg); }}}// Here is the first child component
            const cpn = {
                template: '#cpn'.// Register CCPN component
                components: {
                    ccpn
                },
                data() {
                    return {
                        msg: "I am a message in the CPN component"}},methods: {}};const app = new Vue({
                el: "#app".components: {
                    cpn,
                }
            })
        </script>
        
        </html>
        Copy the code
      • Key code:

            methods: {
                checkParent() {
                    console.log(this.$parent.msg); }}Copy the code
    • $root

      No matter where the component is, the root component properties can be obtained directly:

      • The complete code

        <! DOCTYPEhtml>
        <html lang="en">
        
        <head>
            <meta charset="UTF-8">
            <meta name="viewport" content="Width = device - width, initial - scale = 1.0">
            <title>Document</title>
            <script src=".. /js/vue.js" type="text/javascript"></script>
        </head>
        
        <body>
            <div id="app">
                <cpn ref="son"></cpn>
            </div>
            <! Here are the CPN subcomponents -->
            <template id="cpn">
                <div>
        
                    <div>I am a CPN component</div>
                    <ccpn></ccpn>
                </div>
        
        
        
            </template>
            <! Here is the CCPN component
            <template id="ccpn">
                <div>
                    <div>I am a CCPN component</div>
                    <button @click="checkParent">button</button>
                </div>
            </template>
        </body>
        
        <script>
            // Here are the children of CPN
            const ccpn = {
                template: "#ccpn".methods: {
                    checkParent() {
                        console.log(this.$root.msg); }}}// Here is the first child component
            const cpn = {
                template: '#cpn'.// Register CCPN component
                components: {
                    ccpn
                },
                data() {
                    return {
                        msg: "I am a message in the CPN component"}},methods: {}};const app = new Vue({
                el: "#app".data(){
                    return{
                        msg:"I'm a message for the root component."}},components: {
                    cpn,
                }
            })
        </script>
        
        </html>
        Copy the code
      • The key code

                methods: {
                    checkParent() {
                        console.log(this.$root.msg); }}Copy the code

Five, the slot

5.1 Using common Slots

  • Start by writing slots (
    ) in the child component where you want to change it.

  • Write what needs to be displayed here inside the label of the parent calling component (the call must use a double label)

  • Overall code:

    <! DOCTYPEhtml>
    <html lang="en">
    
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="Width = device - width, initial - scale = 1.0">
        <title>Document</title>
        <script src=".. /js/vue.js" type="text/javascript"></script>
        <style>
            img {
                width: 100px;
                height: 100px;
            }
        </style>
    </head>
    
    <body>
        <div id="app">
            <! -- First slot display button -->
            <cpn> <button>button</button></cpn>
            <! -- The second slot displays images -->
            <cpn> <img src=".. /img/01.png" alt="Personal logo"></cpn>
            <! -- the third slot displays text -->
            <cpn> <span>I am a piece of writing</span></cpn>
        </div>
        <! Here are the subcomponents -->
        <template id="cpn">
            <div>
                <h2>I'm a child component</h2>
                <! Define a slot -->
                <slot></slot>
            </div>
        </template>
    </body>
        
    <script>
        const cpn = {
            template: "#cpn"};const app = new Vue({
            el: "#app".components: {
                cpn
            }
        })
    </script>
    </html>
    Copy the code
  • Key code:

        <div id="app">
            <! -- First slot display button -->
            <cpn> <button>button</button></cpn>
            <! -- The second slot displays images -->
            <cpn> <img src=".. /img/01.png" alt="Personal logo"></cpn>
            <! -- the third slot displays text -->
            <cpn> <span>I am a piece of writing</span></cpn>
        </div>
        <! Here are the subcomponents -->
        <template id="cpn">
            <div>
                <h2>I'm a child component</h2>
                <! Define a slot -->
                <slot></slot>
            </div>
        </template>
    Copy the code

5.2 Default Slot Value

  • The process is the same as above, except that

    is given a default value directly in the child component

  • When invoked, if no slot content is specified, the default slot content is displayed

    <body>
        <div id="app">
            <! -- First slot display button -->
            <cpn> <button>I'm the other button</button></cpn>
            <! -- Second slot default content -->
            <cpn></cpn>
            <! -- the third slot displays text -->
            <cpn> <span>I am a piece of writing</span></cpn>
        </div>
        <! Here are the subcomponents -->
        <template id="cpn">
            <div>
                <h2>I'm a child component</h2>
                <! -- Give the slot a default value -->
                <slot><button>button</button></slot>
            </div>
        </template>
    </body>
    
    Copy the code

5.3 Named Slot

  • Use the name attribute to identify the slot

  • The slot attribute is used at the time of the call to determine which slot to replace

  • If the contents of the identity are not identified by a name, the unnamed slot is searched and replaced

  • If there is no unnamed slot, content with no name specified will not be displayed

  • The overall code

    <! DOCTYPEhtml>
    <html lang="en">
    
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="Width = device - width, initial - scale = 1.0">
        <title>Document</title>
        <script src=".. /js/vue.js" type="text/javascript"></script>
        <style>
            img {
                width: 100px;
                height: 100px;
            }
        </style>
    </head>
    
    <body>
        <div id="app">
            <cpn>
                <! Replace the first slot with a button -->
                <button slot="first">&lt;</button>
                <! -- Replace the second slot with text + input box -->
                <span slot="second">
                    <span>search</span>
                    <input type="text" placeholder="Search">
                </span>
                <! The third slot is empty -->
                <span slot="third"></span>
                <! -- Replace slot without name -->
                <span>Is dubious</span>
                <span>Is dubious</span>
            </cpn>
    
        </div>
        <! Here are the subcomponents -->
        <template id="cpn">
            <div>
                <slot name="first">I was the first slot</slot>
                <slot name="second">I'm the second slot</slot>
                <slot name="third">I'm the third slot</slot>
                <slot></slot>
            </div>
        </template>
    </body>
    
    <script>
        const cpn = {
            template: "#cpn"};const app = new Vue({
            el: "#app".components: {
                cpn
            }
        })
    </script>
    
    </html>
    Copy the code
  • The key code

       <div id="app">
            <cpn>
                <! Replace the first slot with a button -->
                <button slot="first">&lt;</button>
                <! -- Replace the second slot with text + input box -->
                <span slot="second">
                    <span>search</span>
                    <input type="text" placeholder="Search">
                </span>
                <! The third slot is empty -->
                <span slot="third"></span>
                <! -- Replace slot without name -->
                <span>Is dubious</span>
                <span>hey</span>
            </cpn>
    
        </div>
        <! Here are the subcomponents -->
        <template id="cpn">
            <div>
                <slot name="first">I was the first slot</slot>
                <slot name="second">I'm the second slot</slot>
                <slot name="third">I'm the third slot</slot>
                <slot></slot>
            </div>
        </template>
    Copy the code

    If we delete the last unnamed slot in the child component, the above text will not be displayed:

        <! Here are the subcomponents -->
        <template id="cpn">
            <div>
                <slot name="first">I was the first slot</slot>
                <slot name="second">I'm the second slot</slot>
                <slot name="third">I'm the third slot</slot>
            </div>
        </template>
    Copy the code

5.4 Scope slot

  • To bind an attribute name to an attribute value on a slot in a child component with: syntax

    content
    . Attribute names cannot contain uppercase letters

  • The parent needs to write a
    inside the component when called.

  • The overall code

    <! DOCTYPEhtml>
    <html lang="en">
    
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="Width = device - width, initial - scale = 1.0">
        <title>Document</title>
        <script src=".. /js/vue.js" type="text/javascript"></script>
        <style>
            img {
                width: 100px;
                height: 100px;
            }
        </style>
    </head>
    
    <body>
        <div id="app">
            <cpn></cpn>
            <cpn>
                <template slot-scope="slot">
                    <span v-for="item in slot.list">{{item}}-</span>
                </template>
            </cpn>
    
        </div>
        <! Here are the subcomponents -->
        <template id="cpn">
            <div>
                <h2>I'm a child component</h2>
                <slot :list="Arr">
                    <ul>
                        <li v-for="item in Arr">
                            {{item}}
                        </li>
                    </ul>
                </slot>
            </div>
        </template>
    </body>
    
    <script>
        const cpn = {
            template: "#cpn".data() {
                return {
                    Arr: ["xiaoming"."xiaohong"."xiaoguang"]}}};const app = new Vue({
            el: "#app".data() {
                return{}},methods: {},
            components: {
                cpn
            }
        })
    </script>
    
    </html>
    Copy the code
  • Key code:

        <div id="app">
            <cpn></cpn>
            <cpn>
                <template slot-scope="slot">
                    <span v-for="item in slot.list">{{item}}*</span>
                </template>
            </cpn>
    
        </div>
        <! Here are the subcomponents -->
        <template id="cpn">
            <div>
                <h2>I'm a child component</h2>
                <slot :list="Arr">
                    <ul>
                        <li v-for="item in Arr">
                            {{item}}
                        </li>
                    </ul>
                </slot>
            </div>
        </template>
    Copy the code

Six, webpack