第一种:利用props
父组件定义一个number-to-do,传给子组件<com-a>
<com-a number-to-do=5></com-a>
子组件在js中定义props数组
props: ['number-to-do']
就可以在子组件的html中直接取值
{{ numberToDo }}
或者可以定义props对象
props: { 'number-to-do': [Number, String] }
来指定传来的值是数字还是字符串
第二种:利用插槽(并不是传值,只是会在子组件渲染显示)
父组件在子组件内部写入数据
<com-a>
<p>123</p>
</com-a>
子组件在html中写入
<slot></slot>
就可以实现将父组件中写入的数据传给子组件
我们也可以通过对<slot>
进行定义属性来指定插槽位置
父组件中这样写:
<com-a>
<p slot="oneslot">123</p>
<p slot="twoslot">456</p>
</com-a>
子组件中这样写:
<slot name="oneslot">i am oneslot</slot>
<p>乱七八糟</p>
<slot name="twoslot">i am twoslot</slot>
当指定的slot没有被引用时,就展示slot标签中的默认值
第三种:子组件来触发emit事件
在子组件中定义一个方法
<button @click="emitMyEvent">emit</button>
emitMyEvent () {
this.$emit('my-event', this.hello)
}
在父组件中监听这个emit事件
<com-a @my-event="getMyEvent"></com-a>
getMyEvent (hello) {
console.log('i get my event' + hello)
}
网友评论