vue中父子组件的参数传递和应用示例

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

vue中父子组件的参数传递和应用示例

归尘2016   2021-01-04 我要评论
这篇文章主要介绍了vue中父子组件的参数传递和应用示例,帮助大家更好的理解和使用vue框架,感兴趣的朋友可以了解下

1.在父组件中调用子组件,父亲传值给子组件

子组件如下,把要传给给父亲的值放在props中

template>
  <!--底部导航-->
  <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>

父组件的调用的三部曲

首先引入子组件

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

注入组件在components中注入

components: {Bottom}

在父亲中应用

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

到这里就结束了,是不是贼快

2.子组件传值给父组件

父组件在组件上定义了一个自定义事件childFn,事件名为parentFn用于接受子组件传过来的message值。

<!-- 父组件 -->
<template>
  <div class="test">
   <test-com @childFn="parentFn"></test-com>
   <br/> 
   子组件传来的值 : {{message}}
  </div>
</template>

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

子组件是一个buttton按钮,并为其添加了一个click事件,当点击的时候使用$emit()触发事件,把message传给父组件

<!-- 子组件 -->
<template> 
<div class="testCom">
  <input type="text" v-model="message" />
  <button @click="click">Send</button>
</div>
</template>
<script>
export default {
  // ...
  data() {
    return {
     // 默认
     message: '我是来自子组件的消息'
    }
  },
  methods: {
   click() {
      this.$emit('childFn', this.message);
    }
  }  
}
</script>

在子组件向父亲传值的时候,不可用router-link,不然接受不到父亲定义的函数

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们