Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

preface

Eat enough to write code

Today to reason a Vue component between the father and son components of the mutual value of the logic, understanding is actually very simple, but like us such beginners may also have confusion or not skilled in the actual use of the place, the reference to the code on the Internet to record this, convenient use of the time reference!

The parent component passes data to the child component

For the child component, props:[parameter name] is used as the parameter value from the parent component.

The parent component calls the child component, using V-bind to bind the required value of the parameter passed to the child component;

// Subcomponent:
<template>
    <header class = "header">
        <div id="logo">{{logo}}</div>
        <ul class="nav">
            <li v-for="nav in navs">{{nav.li}}</li>
        </ul>
    </header>
</template>
<script>
    export default{
        name: 'headerDiv'.data(){
            return{
                navs:[
                    {li:'home'},
                    {li:'log'},
                    {li:'about'},
                    {li:'album'}}},],props: ['logo']
        //props:{
        // logo: String,
        // required: true
        / /}
    }
</script>
Copy the code
/ / the parent component
<template>
    <div id = "app">
        <HeaderDiv :logo="logoMsg"></HeaderDiv>
    </div>
</template>
<script>
    import HeaderDiv from './components/header'
    export default{
        name: 'app'.data(){
            return{
                logoMsg: 'Hello World'}},components:{
            HeaderDiv
        }
    }
</script>
Copy the code

Child component passing data to parent (publish-subscribe mode)

A $emit custom event is used in the child component to pass the value to the parent component

The parent component calls the method with this event to get the parameter values passed in by the child component

<template>
    <section>
        <div class="login">
            <label>
                <span>User name:</span>
                <input v-model="name" @change="setName"/>
            </label>
        </div>
    </section>
</template>
<script>
    export default{
        name: 'login'.data(){
            return{
               name: ' '}},methods: {setName: function(){
               this.$emit('transferName'.this.name)
           }
       }
    }
</script>
Copy the code
/ / the parent component
<template>
    <div id="app">
        <LoginDiv @transferName="getName"></loginDiv>
        <p>User name: {{name}}</p>
    </div>
</template>
<script>
    import LoginDiv from './components/login'
    export default{
        name: 'app'.data(){
            return{
                name: ' '}},components:{
            LoginDiv
        },
        methods: {getName(msg){
               this.name = msg
           }
       }
    }
</script>
Copy the code