1. 子组件传父组件
子组件
<li class="smaili" v-for="(item,index) in MonitorList" :key="index"> <input type="checkbox" id="jack" :value="item.monitoringPointName" v-model="checkedNames"> <label class="oneMenuChild" for="jack" @click="sendMsg(item.monitoringPointAddress)">{{item.monitoringPointName}}</label> </li>
@click="sendMsg(item.monitoringPointAddress)点击子组件的时候传值给父组件
sendMsg(videoUrl){ // this.$emit('getVideoUrl',videoUrl) this.$emit('getVideoUrl',videoUrl) }
父组件接收
<div class="jkmenuaaa" > <jkmenu @getVideoUrl="videoUrlFn" ref="sun"/> //对应子组件自动执行getVideoUrl
</div>
videoUrlFn(data){ console.log(data) this.monitorUrl = data this.videoPlay() },
let chil =
this
.$refs.sun //父组件可以通过$refs拿到子组件的对象,然后直接调用子组件methods里的方法和data里的数据
2. 父组件传子组件
父组件
:currScenicId="currid" //要传递的数据
<div class="pop_con"> <yjyd1 class="con" :currScenicId="currid" v-show="iconNowIndex===2"/> <yjyd2 class="con" v-show="iconNowIndex===0"/> </div>
子组件
export default{ props: ['currScenicId'] }
全局事件实现兄弟组件传参
$emit('自定义事件名', 要传送的数据)
$on('对应自定义事件名', 回调函数)
home.vue中引入a和b组件, 实现a.vue向b.vue传送一句话
main.js 挂载$bus
new Vue({ el: '#app', router, components: { App }, template: '<App/>', beforeCreate(){ Vue.prototype.$bus = this //通过全局事件传参 } })
home.vue
<template> <div> <com1></com1> <com2></com2> </div> </template> <script> import com1 from '@/components/components/a.vue' import com2 from '@/components/components/b.vue' export default { name: 'HelloWorld', components: { com1,com2 }, data () { return { } } } </script>
a.vue
<template> <div> <h3 @click="showName('name111111')">name1</h3> <div>{{name}}</div> <div @click="sendMessage()">向b传送数据</div> </div> </template> <script> import {minxinName} from '@/mixin.js' export default { mixins: [minxinName], data(){ return{ name } }, methods: { sendMessage(){ this.$bus.$emit('toB', '暗恋不是一个人的事情') } } } </script>
b.vue
<template> <div> <h3 @click="showName('name222222')">name2</h3> <div>{{name}}</div> <div>获取a页面中的数据:{{getToB}}</div> </div> </template> <script> import {minxinName} from '@/mixin.js' export default { mixins: [minxinName], data(){ return{ name, getToB: '' } }, mounted(){ console.log(this) this.$bus.$on('toB',(data)=>{ this.getToB = data }) }, beforeDestroy(){ this.$bus.$off('toB') //用完以后销毁toB } } </script>
*a, b页面中同时实现混入功能(相同的事件功能)*
src下新建mixin.js
export let minxinName = { methods: { showName: function (name1){ this.name = name1 } } }