如何从组件获取数据

时间:2019-02-24 04:22:40

标签: vue.js

我是Vue.js的新手。

list.vue:

<template>
  <div class="m-products-list">
    <ul @mouseover="over">
      <Item
        v-for="(item,idx) in parentList"
        location="item.location"
        :key="idx"
        :meta="item"/>
    </ul>
  </div>
</template>

<script>
export default {
  ...
  methods: {
    over: function (e) {
      let dom = e.target;
      let tag = dom.tagName.toLowerCase();
      if (tag === 'dd') {
        console.log(dom.getAttribute('location'))
      }
    }
  }
}
</script>

Item来自其父组件。而且,当我将鼠标悬停在item.location上时,我想在over()中获得item,但是console.log总是返回null。有人有主意吗?

1 个答案:

答案 0 :(得分:1)

通过在Item中设置data-* attribute,这在技术上是可行的(但下一节可能会有更好的选择)。

// Item.vue
<li :data-location="location" class="item" ... >

new Vue({
  el: '#app',
  data() {
    return {
      items: [
        {id: 1, location: 'New York'},
        {id: 2, location: 'Los Angeles'},
        {id: 3, location: 'Chicago'},
      ]
    }
  },
  components: {
    Item: {
      props: ['location'],
      template: `<li :data-location="location" class="item">{{location}}</li>`,
    }
  },
  methods: {
    over(e) {
      console.log(e.target.dataset.location)
    }
  }
})
<script src="https://unpkg.com/vue@2.6.7/dist/vue.min.js"></script>

<div id="app">
  <ul @mouseover="over">
    <Item v-for="item in items"
          :key="item.id"
          :location="item.location" />
  </ul>
</div>

不需要DOM操作的更好的解决方案是在Vue中使用数据模型并将mouseover事件侦听器移动到Item

  1. over()的参数更改为位置名称(以前是事件对象):

    methods: {
      over(location) {
        /* ... */
      }
    }
    
  2. @mouseover事件侦听器批注从ul移动到模板中的Item,并将item.location作为参数传递:

    <ul>
      <Item v-for="item in items" @mouseover="over(item.location)" ... />
    </ul>
    
  3. 编辑Item的模板以将其mouseover事件转发给父对象:

    // Item.vue
    <li @mouseover="$emit('mouseover', $event)" ... >
    

new Vue({
  el: '#app',
  data() {
    return {
      items: [
        {id: 1, location: 'New York'},
        {id: 2, location: 'Los Angeles'},
        {id: 3, location: 'Chicago'},
      ]
    }
  },
  components: {
    Item: {
      props: ['location'],
      template: `<li @mouseover="$emit('mouseover', $event)" class="item">{{location}}</li>`,
    }
  },
  methods: {
    over(location) {
      console.log(location)
    }
  }
})
<script src="https://unpkg.com/vue@2.6.7/dist/vue.min.js"></script>

<div id="app">
  <ul>
    <Item v-for="item in items"
          :key="item.id"
          :location="item.location"
          @mouseover="over(item.location)" />
  </ul>
</div>