1

emits: 列表声明从父组件继承来的事件
$emit: 抛出事件, 通知父组件处理
在子组件中,通过$emit()来触发事件
在父组件中,通过v-on来监听子组件事件
子组件中:


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)    
      })
    
    })
  },
  
}

父组件中

                <my-xg-player 
                :dom-id="'xgplayer_test_'+file.collection_id"
                  :preview-video-url="file.file_path"
                  @justOnePlayer="justOnePlayer"
                  />
<!--script中-->
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

CUI_PING
42 声望3 粉丝