vue3 中使用emits

emits: 列表声明从父组件继承来的事件
$emit: 抛出事件, 通知父组件处理
子组件中:


export default {
  name: "MyXgPlayer",
  //声明从父组件继承来的事件:可以是简单数组, 也可以是对象(加了校验函数)
  emits: ['just-one-player'],
  props:{
    domId: String,
    previewVideoUrl: String,
   
  },
  setup(props, context){
    //获取当前实例(包括从父组件传过来的props数据, 实例方法($watch,$emit, $forceUpdate,$nextTick, 定义的全局的$addHost
    // vue 内含的$alert,$message,$messageBox, $store,$router, $refs ...))
    const {proxy} = getCurrentInstance()
     
    let player = ref(null)
    onMounted(()=>{
        //new 数据
        player.value = new Player ({
        id: props.domId,
        url: props.previewVideoUrl,
      
      });
      //监听play 事件
      player.value.on('play', ()=>{
        console.log("start $emit")
        //给父组件抛事件
        proxy.$emit("just-one-player", props.domId, player)    
      })
    
    })
  },
  
}

父组件中

                

import {ref} from "vue"
setup(props, context){
   const xgplayers = ref({})
   const justOnePlayer = (domId, player)=>{
          console.log("receive $emit")
          for(let item_key in state.xgplayers){
            if(item_key !== domId){
              state.xgplayers[item_key].pause()
            }
          }
          state.xgplayers[domId] = player
        }
    return {
        xgplayers,
        justOnePlayer
      }
    }
}

点击子组件中的播放,打印的log

start $emit
receive $emit

你可能感兴趣的:(vue.js)