Передача события из одного компонента в другие компоненты - PullRequest
0 голосов
/ 05 октября 2018

Я действительно новичок в Vue и, похоже, не могу понять, как событие передается от одного компонента к другим компонентам.В настоящее время я использую v-blur , и я хочу размыть каждый компонент, кроме одного, на который нажали.Я решил передать событие другим компонентам при нажатии на оригинальный компонент, чтобы получить желаемый эффект.Любая помощь очень ценится!

// Parent.vue
<template>
  <div id="Parent">
    <child-one @toggle-blur="toggleChildBlur"/>
    <child-two @toggle-blur="toggleChildBlur"/>
    <child-three @toggle-blur="toggleChildBlur"/>
  </div>
</template>

<script>
import ChildOne from './ChildOne'
import ChildTwo from './ChildTwo'
import ChildThree from './ChildThree'

export default {
  name: 'Parent',
  components: {
    ChildOne, ChildTwo, ChildThree
  },
  methods: {
    toggleChildBlur () {
      // Blur every child except the clicked one?
    }
  },
  data () {
    return {}
  }
}
</script>  

// ChildOne.vue, basically the same for two and three aswell
<template>
  <div id="child-one" v-blur="blurConfig" @click="$emit('toggle-blur')"></div>
</template>

<script>
export default {
  name: 'ChildOne',
  methods: {
    toggleBlur () {
      this.blurConfig.isBlurred = !this.blurConfig.isBlurred;
    }
  },
  data () {
    return {
      blurConfig: {
        isBlurred: false,
        opacity: 0.3,
        filter: 'blur(1.2px)',
        transition: 'all .3s linear'
      }
    }
  }
}
</script>

Ответы [ 2 ]

0 голосов
/ 06 октября 2018

Я нашел способ получить эффект, который хотел в итоге.Мое решение может быть не очень масштабируемым, но пока работает!Я передаю дочерний индекс от эмиттера и зацикливаюсь, чтобы размыть каждый компонент, кроме индексированного дочернего индекса.

// ChildOne.vue
// Basically the same for two and three as well except sending corresponding index
// on click event.

// Click event is now sending the index of the component to know which one got clicked.
<template>
  <div id="child-one" @click="$emit('toggle-blur', 0)"></div>
</template>

// Parent.vue

// Every child component now gets their separate blur config.
// When child is clicked the index of the child now gets sent to help skip and blur
// the other components.
<template>
  <div id="parent">
    <child-one v-blur="blurConfig[0]" @toggle-blur="toggleChildBlur"/>
    <child-two v-blur="blurConfig[1]" @toggle-blur="toggleChildBlur"/>
    <child-three v-blur="blurConfig[2]" @toggle-blur="toggleChildBlur"/>
  </div>
</template>

<script>
import ChildOne from './ChildOne'
import ChildTwo from './ChildTwo'
import ChildThree from './ChildThree'

export default {
  name: 'Parent',
  components: {
    ChildOne, ChildTwo, ChildThree
  },
  methods: {
    toggleChildBlur (childIndex) {
      // Unblur if click event is outside focused component
      if (this.blurConfig[childIndex].isBlurred) {
        for (let i = 0; i < this.blurConfig.length; i++) {
          this.blurConfig[i].isBlurred = false
        }
      } else {
        for (let i = 0; i < this.blurConfig.length; i++) {
          if (i !== childIndex) {
            this.blurConfig[i].isBlurred = !this.blurConfig[i].isBlurred
          }
        }
      }
    }
  },
  data () {
    return {
      // Blur settings for each component
      blurConfig: [
        {
          isBlurred: false,
          opacity: 0.2,
          filter: 'blur(1.2px)',
          transition: 'all .2s linear'
        },
        {
          isBlurred: false,
          opacity: 0.2,
          filter: 'blur(1.2px)',
          transition: 'all .2s linear'
        },
        {
          isBlurred: false,
          opacity: 0.2,
          filter: 'blur(1.2px)',
          transition: 'all .2s linear'
        }
      ]
    }
  }
}
</script>
0 голосов
/ 05 октября 2018

События, отправленные в Vue, перемещаются в одном направлении: ребенок ⇒ родитель.Если у вас есть компонент P (родительский) и дочерний элемент C1 (дочерний элемент 1) и C2 (дочерний элемент 2), невозможно вызвать событие в C1 и отправить его в C2.Это перейдет к P.

Если у вас очень вложенная структура (много уровней) и вам действительно нужно это сделать, самый простой способ сделать это - отправлять и прослушивать события на чем-то, что не является частьюсписок отображения, т.е. что-то глобальное.Очень типичное решение - иметь так называемую «шину событий» - отдельный фиктивный экземпляр Vue, который вы используете только для событий.Вот полный учебник о Global Event Bus в Vue .

. Это выглядит примерно так:

// in some global file
const EventBus = new Vue();

// in GC1 (parent -> child 1 -> grand child 1)
EventBus.$emit('someEvent', 'some-data')

// in GC5 (parent -> child 3 -> grand child 5)
EventBus.$on('someEvent', function(data) {
  console.log(data) // 'some-data
})

Таким образом, вы можете легко отправлять / перехватывать события по всемуместо.

Удачи!:)

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...