Parameter passing and application example of parent child component in vue

  • 2021-10-16 00:43:28
  • OfStack

1. Call the child component in the parent component, and the parent passes the value to the child component

The child component is as follows, and the value to be passed to the parent is placed in props


template>
  <!-- Bottom navigation -->
  <div class="index-bbar">
    <ul class="flex" >
      <li v-for="(item,index) in liAry" :class="index==licurrent?'active':''">
       <router-link :to="item.linkURl">
        <span class="flex alignc flexdc">
          <img :src="index==licurrent?require('../../' + item.urlActive):require('../../' + item.url)" class="img1" ><span>{{item.title}}</span>
        </span>
       </router-link>
      </li>
    </ul>
  </div>
</template>
<script>
export default {
 name: 'Bottom',
 data () { 
  return {
    
  }
 },
 props:['liAry','licurrent'],
 methods: {

 }
}
</script>
<style scoped>
@import "../../assets/public/css/top.css";
@import "../../assets/public/css/bottom.css";
</style>

3 parts of the call to the parent component

First, introduce subcomponents


import Bottom from '@/components/public/Bottom';

Injection component is injected in components


components: {Bottom}

Apply in fathers


<template>
<Bottom v-bind:liAry='lidata' v-bind:licurrent='guidecurrent'></Bottom>
</template>

It's over here, isn't it quick

2. Child components pass values to parent components

The parent component defines a custom event childFn on the component named parentFn to accept the message value passed from the child component.


<!--  Parent component  -->
<template>
  <div class="test">
   <test-com @childFn="parentFn"></test-com>
   <br/> 
    Values from subcomponents  : {{message}}
  </div>
</template>

<script>
export default {
  // ...
  data: {
    message: ''
  },
  methods: {
    parentFn(payload) {
    this.message = payload;
   }
  }
}
</script>

The child component is an buttton button and adds an click event. When clicked, use $emit () to trigger the event and pass message to the parent component


<!--  Subcomponent  -->
<template> 
<div class="testCom">
  <input type="text" v-model="message" />
  <button @click="click">Send</button>
</div>
</template>
<script>
export default {
  // ...
  data() {
    return {
     //  Default 
     message: ' I am a message from a subcomponent '
    }
  },
  methods: {
   click() {
      this.$emit('childFn', this.message);
    }
  }  
}
</script>

router-link cannot be used when the child component passes values to the parent, otherwise the function defined by the parent cannot be accepted

Above is the vue Parameter Parameter Transfer and Application Example Details, more on vue Parameter Transfer Parameter Data please pay attention to this site other related articles!


Related articles: