2.7 组件(2)
- props从父组件向子组件通信,自定义事件的目的是完成子组件向父组件信息传递
childComponents
1.1.<button @click='$emit("put","ages")'></button>
parentComponents
template
中
1.2.<com age='ages' @put="put" />
script
中
method:{
put:function(a){
//1.3
windows.console.log(this.ages,a)
}
}
最后结果 18 'age'
- 1.1"ages"为传入的参数,在parentComponents中,对应形参a,这里不能输入ages,输入后无法正常引用data中定义的age
- 1.2与1中对应的内容,如果想正常使用ages,需要再method中直接使用
- 1.3注意在父和子组件中,事件的写法
- slot的使用
2.1 在vue,template
中标签不能嵌套使用,如需临时添加H5标签,则需要使用slot
2.2 在<com :age='ages' @put='put'>...</com>
中不能直接插入类似<h1>这类h5的标签,在子组件中使用插槽<slot></slot>
则可以使用,需要一一对应
2.3 在父组件嵌套的子组件模板中可以按照以下方式改下
<h1 slot="a">something</h1>
<h1 slot="a">something</h1>
在子组件中可以写入以下插槽
<slot name="a"></slot>
<slot name="b"></slot>
- 困惑,明白props和自定义事件的基本写法,现在还不太明白这样做的原理或者意义何在