当前位置:主页 > 查看内容

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

发布时间:2021-05-28 00:00| 位朋友查看

简介: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.li……

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,不然接受不到父亲定义的函数

以上就是vue中父子组件的参数传递和应用示例的详细内容,更多关于vue中父子组件的参数传递的资料请关注站长技术其它相关文章!


原文链接:https://m.jb51.net/article/203404.htm
本站部分内容转载于网络,版权归原作者所有,转载之目的在于传播更多优秀技术内容,如有侵权请联系QQ/微信:153890879删除,谢谢!
上一篇:js用正则表达式筛选年月日的实例方法 下一篇:没有了

推荐图文


随机推荐