Vue中父子组件之间值的传递

1、正向传递,由父组件→子组件传值,不需要条件触发,是主动传递的;在子组件定义props,然后在父组件传入即可,如:

//在子组件内定义props
<script>
export default {
  props:['mark','sel']
</script>
<template><!--在父组件内传入mark、sel-->
<Item txts="首页" mark="1" :sel='selected'>
          <img src="../assets/img/1.png" slot="normalimg"/>
          <img src="../assets/img/6.png" slot="activeimg"/>
      </Item>
</template>

2、逆向传递,由子组件→父组件传值,需要通过自定义事件触发;

抛出自定义事件监听的语法:

this.$emit('event',val)
//event:自定义事件的名称
//val:传入的值(可选填,可以不填)

父组件上接受自定义事件监听的语法:

<template>
 <component @event='fn'>
 </component>
</template>
<!--
component:任意组件
event:自定义监听事件的名称
fn:此处的方法名后面不写小括号
-->


<script>
export default{
 methods:{
 fn:function(val){}
 //val:自定义事件从子组件传来的值
 }
}
</script>

猜你喜欢

转载自my.oschina.net/u/3648322/blog/1805795