webveuje/vue/组件间通信.md
2020-12-23 16:51:20 +08:00

95 lines
1.8 KiB
Markdown
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# 组建间通信
### 父组件往子组件传值prop
子组件中使用prop 定义从父组件接收的值
父组件调用子组件时, 子组件prop里面定义的值就变成了父组件从实例 template部分变成属性
props语法
- 对象格式定义
props:{
属性名:{
type 数据类型
default: 默认值
}
}
```
<div id="app">
<counter msg="父组件传过来的值1"></counter>
<counter msg="父组件传过来的值2"></counter>
<counter msg="父组件传过来的值3"></counter>
<counter msg="父组件传过来的值4"></counter>
</div>
<script>
let counter=Vue.component('counter', {
data: function () {
return {
count: 0
}
},
props:{
msg:{
type:String
}
},
methods:{
add(){
this.count+=1
}
},
template: '<div>{{msg}}</div>'
})
var app = new Vue({
el: '#app',
component:{
counter
}
})
</script>
```
- 数组格式定义Props
props: ['属性名'],
上面的Props重新定义为
```
props:['msg']
```
### 子组件往父组件传值($emit
在子组件的template部分中触发事件事件处理函数内部 写入
```
this.$emit('drag<监听这个事件的所用的名称>',要传的值)
```
然后从父组件的template部分做如下处理
```
<counter @timend="end"><counter>
其中 timeend 是监听这个end这个时间所用的名称
end是触发timeend之后的处理函数名
```