传值
- 父组件传值给子组件
// 父组件
<template>
<div>
<!-- 父组件中引入子组件,并传入子组件内需要的值 -->
<child :message="father"></child>
</div>
</template>
<script>
import child from './child'
export default {
data() {
return {
//定义需要传入的值
father: '传给子组件的值'
}
},
components: {
child
}
}
</script>
// 子组件
<template>
<div>
<div>{{message}}</div>
</div>
</template>
<script>
export default {
//在子组件中注册props,并使用父组件中传递过来的数据
props: {
message: String
},
}
</script>
- 子组件传值给父组件
// 父组件
<template>
<div>
<!--自定义事件child,事件名为parent(parent事件用于接收子组件传递过来的值)-->
<parent @child="parent"></parent >
</div>
</template>
<script>
export default {
data: {
message: ''
},
methods: {
parent(val) {
this.message = val;
}
}
}
</script>
// 子组件
<template>
<div>
<!--点击按钮触发send事件,把message传给父组件-->
<button @click="send">Send</button>
</div>
</template>
<script>
export default {
data() {
return {
message: '我是子组件的消息'
}
},
methods: {
sendMes() {
this.$emit('child', this.message);
}
}
}
</script>
调用方法
- 父组件调用子组件的方法
// 父组件
<template>
<div @click="handleParent">
<children ref="mychild"></children>
</div>
</template>
<script>
import children from 'children.vue'
export default {
components: {
children
},
methods:{
handleParent() {
this.$refs.mychild.childMethod();
}
}
}
</script>
// 子组件
<template>
<div></div>
</template>
<script>
export default {
methods:{
childMethod() {
console.log('My name is child')
}
}
}
</script>
- 子组件调用父组件的方法
// 父组件
<template>
<div>
<child @listenChild="showFrom"></child>
<div>{{ value }}</div>
</div>
</template>
<script>
import child from './compontents/child.vue'
export default {
components:{child},
data () {
return {
value:''
}
},
methods: {
showFrom(data){
this.value = data
},
}
}
</script>
//子组件
<template>
<button @click="send()">
我是子组件,点击我向父组件传值
</button>
</template>
<script>
export default {
data(){
return {
message:'子组件的数据'
}
},
methods:{
send() {
this.$emit("listenChild",this.message)
}
}
}
</script>
非父子组件
- 广播自定义事件
handleClick(){
//response为要传的值
this.$root.$emit('change',response)
}
- 处理自定义事件
handleClick(){
this.$root.$on('change',(item)=>{
console.log(item) //item就是广播事件的response
})
}
有时候会发生事件只被 emit 触发了一次,但是回调函数却被执行了多次的现象。这种现象往往发生在页面跳转退出后重新进入的时候。
产生原因:this. r o o t . B u s . root.Bus. root.Bus.on 实际是向 Bus 容器中添加一个事件监听器,当页面跳转时,原来的 vue 组件被注销,但是原来 vue 组件向 Bus 容器中添加的事件监听器并不会被移除。因此,当下次进入这个 vue 组件对应的页面时,执行到 this. r o o t . B u s . root.Bus. root.Bus.on 时,又会向 Bus 容器中添加一个重复的事件监听器,以此类推,导致 Bus 容器中有很多个一模一样的事件监听器,从而导致事件只被触发一次,但是回调函数被执行多次的现象。
解决方案:在 vue 组件的 beforeDetory 钩子函数中将本 vue 组件往 Bus 容器中添加的时间监听器全部手动移除。
//在vue对象的methods域中定义个函数专门移除事件监听器
offListener() {
this.$root.Bus.off("事件名");
this.$root.Bus.off("事件名");
this.$root.Bus.off("事件名");
},
//在beforeDestroy钩子中调用此函数
beforeDestroy() {
this.offListener();
},