Home > Enterprise >  Vue3 how to bind custom event to specific component in router-view?
Vue3 how to bind custom event to specific component in router-view?

Time:07-25

this is my App

//App.vue
<template>
  <Header ref="header"></Header>
  <RouterView @emitDelet="deleteHeader"> 
  </RouterView>>
  <Footer></Footer>
</template>

this is my route, router-viewcontains three components.

[
  {
    path: '/home',
    name: 'home',
    component: Home,
    meta: {
      showFooter: true,
    },
  }, //
  {
    path: '/search',
    name: 'search',
    component: Search,
    meta: {
      showFooter: true,
    },
  },
  {
    path: '/Login',
    name: 'login',
    component: Login,
    meta: {
      showFooter: false,
    },
  }
]

I only want to bind custom event to search component, how should I do. If I bind it to router-view,I need to defineEmits in every component to avoid warning in devtool although it doesn't affect work.

CodePudding user response:

I see that the best approach is to use the inject/provide pattern :

in App.vue :

<template>
  <Header ref="header"></Header>
  <RouterView> 
  </RouterView>>
  <Footer></Footer>
</template>
<script setup>
import { provide } from 'vue'

function deleteHeader(){
//....
}

provide('deleteHeader',deleteHeader)

</script>

in Search component :

<script setup>
import { inject } from 'vue'

const deleteHeader = inject('deleteHeader')

//then you could run it like `deleteHeader` instead of emit('emitDelet')
</script>
  • Related