即使我可以在Vue控制台中看到事件触发,但是当事件$ emit被激活时,Vue $ on没有运行我的函数

时间:2017-08-30 14:22:53

标签: javascript events vue.js vuejs2

我正在尝试测试我的$on功能是否有效。我可以清楚地看到Vue控制台正在接收事件发射,但$on中的预定义回调函数未被调用。

以下是代码:

<template lang="html">
  <div class="test">
    <Filters></Filters>
  <div>
    <ul class="o-list c-stores">
      <Result v-bind:total="filteredRestuarants.length" v-bind:open="isOpen" v-on:toggle="toggleRestaurantList"></Result>
      <li v-for="(restaurant, index) in filteredRestuarants" class="c-stores__location" :class="{'first': isFirst(index), 'last': isLast(index, restaurants)}">
        <Location :index="index" :store="restaurant" :link="() => setCurrentRestaurant(restaurant)"></Location>
      </li>
    </ul>
  </div>
  </div>
</template>

<script>
import eventHub from './../../event-hubs/storefinder'
import Location from './Location'
import Filters from './Filters'
import Result from './Result'

export default {
  props: ["restaurants", "isOpen", "currentSearch"],
  data() {
    return {
      attributes : [],
    }
  },
  head: {
    title: function () {
      return {
        inner: this.$t('storefinder.overview')
      }
    },
    meta: function functionName() {
      return [{
          name: 'og:title',
          content: this.$t('storefinder.overview') + ' - ' + this.$t('storefinder.name'),
          id: "og-title"
        },
        {
          name: 'description',
          content: this.$t('storefinder.description'),
          id: "meta-description"
        },
        {
          name: 'og:description',
          content: this.$t('storefinder.description'),
          id: "og-description"
        },
      ]
    }
  },
  components: {
    Location,
    Filters,
    Result
  },
  computed: {
    filteredRestuarants(rest) {
      let restaur = rest || this.restaurants;
      return this.restaurants;
    }
  },
  methods: {
    startEvents(){
      eventHub.$on('addFilterTheRestaurants', (attribute) => {console.log("test")});
      eventHub.$on('removeFilterTheRestaurants', (attribute) => {console.log("test")});
    },
    toggleRestaurantList() {
      eventHub.$emit('showRestaurantList');
    },
    setCurrentRestaurant(restaurant) {
      this.trackRestaurantSelect(restaurant.publicNameSlug);
      this.$router.push({
        name: "store",
        params: {
          restaurant: restaurant.publicNameSlug
        }
      });
    },
    trackRestaurantSelect(restaurantName) {
      dataLayer.push({
        'event': 'GAEvent',
        'eventCategory': 'restaurants',
        'eventAction': 'clickResult',
        'eventLabel': restaurantName,
        'eventValue': undefined,
        'searchTerm': this.currentSearch && this.currentSearch.toLowerCase(),
        'amountSearchResults': 1
      });
    },
    created() {
      this.startEvents()
      // eventHub.$on('addFilterTheRestaurants', (attribute) => this.filteredRestuarants.value = this.restaurants.forEach(rest => {console.log(rest)}));
      // eventHub.$on('addFilterTheRestaurants', (attribute) => {console.log("test")});
      // eventHub.$on('removeFilterTheRestaurants', (attribute) => {console.log("test")});
    },
    beforeDestroy () {
      bus.$off('addFilterTheRestaurants')
      bus.$off('removeFilterTheRestaurants')
    },
    isLast: function (idx, list) {
      return idx === list.length - 1;
    },
    isFirst: function (idx) {
      return idx === 0;
    },
  }
}
</script>

在这里被发现:

<template lang="html">


<div class="c-filters">
    <div class="c-filters-list">
  // Here I call the function to $emit my event
      <div class="c-filters__item" v-for="item in filters" @click="(e) => {toggleClass(e); addFilter(item)}"> 
        {{$t(`storefinder.store.attributes.${item}`)}}
      </div>
    </div>
  </div>
</template>

<script>
import {getKeys} from './../../i18n/'
import eventHub from './../../event-hubs/storefinder'
import notificationHub from './../../event-hubs/notification'
import GLSApi from './../../api/gls'

export default {
  data() {
    return {
      attributes: null,
      filters : [
        "WIFI",
        "TABLESERVICE",
        "MCCAFE",
        "INDOORDINING",
        "DRIVETHRU",
        "BREAKFAST",
        "MALEFEMALEHANDICAPACCESSIBLE",
        "BABYCHANGING",
        "BIRTHDAYPARTIES",
        "SELFORDERKIOSK",
        "OUTDOORPLAYGROUND",
        "INDOORPLAYGROUND",
        "JUNIORCLUB"
      ]
    }
  },
  computed: {
    getAttributes() {
      let arr = this.attributes.map(elem => elem.storeAttributes.attribute)
      return arr.map((el,index, array) => array[index].map(obj => obj.type))
    }
  },
  methods: {
    toggleClass(e){
      e.target.classList.contains("add-filter") ? e.target.classList.remove("add-filter") : e.target.classList.add("add-filter") ;
    },
 // here it the $emit happening
    addFilter (item) {
      eventHub.$emit('addFilterTheRestaurants', item);
    },
    deleteFilter (item) {
      eventHub.$emit('removeFilterTheRestaurants', item);
    }
  },
  beforeCreate() {
    eventHub.$on('attributesLoaded', (params) => this.attributes = params);
  }
}
</script>

1 个答案:

答案 0 :(得分:1)

您在计算财产中注册了addFilterTheRestaurants事件。但是,计算出的属性&#39;除非引用计算属性,否则不调用函数。由于您从不引用this.startEvents,因此永远不会执行该函数。

您可以整天发出addFilterTheRestaurants事件,但由于您尚未注册该事件,因此不会发生任何事情。

只需在$on挂钩中注册created处理程序即可。或者使startEvents成为方法而不是计算属性,并在created挂钩中调用它。但是,请确保指定created生命周期挂钩,而不是名为created的方法。