[Vuejs]-How to let the parent component trigger the event of the child component without using refs in VueJs

0👍

You can try with scoped slot, prop and watcher:

const app = Vue.createApp({})
app.component('parent', {
  template: `
    <div>
      <button @click="trigger = true">evt</button>
      <slot :trig="trigger"></slot>
    </div>
  `,
  data: () => ({
    trigger: false,
  }),
})
app.component('child', {
  template: `
    <div>{{ evt }}</div>
  `,
  props: {
    trig: {
      type: Boolean,
      default: false
    }
  },
  data: () => ({
    evt: 'a',
  }),
  watch: {
    trig(val) {
      if(val) this.trigEvt()
    }
  },
  methods: {
    trigEvt() {
       this.evt = 'b'
    }
  }
})
app.mount('#demo')
<script src="https://unpkg.com/vue@3/dist/vue.global.prod.js"></script>
<div id="demo">
  <template v-for='item in 7'>
    <parent>
      <template v-slot="{trig}">
        <child :trig="trig"></child>
      </template>
    </parent>
  </template>
</div>

Leave a comment