我如何将数据从子组件发送到Vue中的父脚本部分?

时间:2019-06-13 14:59:47

标签: vue.js vue-component

我需要创建对象或数组,以将其从Vue.js中的父组件发送到RETS API。

我尝试使用$ emit方法,但是它对我不起作用

结果,我想在父组件中获得一个数组,如下所示: 'property1':'value1', 'property2':'value2'

有人知道我该怎么做吗?

我的孩子部分

Referer

我的父组件代码:

<script>
import StarRating from 'vue-star-rating';

/**
 * Звезды рейтинга с надписью
 *
 * @type {{}}
 */
export default {
  name: 'StarsWithLabel',

  components: {
    StarRating,
  },

  data: function () {
    return {
      rating: 0,
    };
  },

  props: {
    label: String,
    property: String,

    state: {
      type: Boolean,
      default: true
    }
  },

  methods: {
    setCurrentSelectedRating: function(rating) {
      this.$emit('sent-rating-in-parent', 'You have Selected: ' + rating + ' stars for ' + property);
    }
  }

};

</script>

<template>
    <div>
        <label id="property">{{label}}</label>
        <star-rating v-bind:star-size="20"
                     v-bind:increment="0.01"
                     v-bind:max-rating="5"
                     v-bind:fixed-points="2"
                     v-model = "rating"
                     @rating-selected="setCurrentSelectedRating"
        >
        </star-rating>
    </div>
</template>

1 个答案:

答案 0 :(得分:0)

listener属性的放置位置应在子组件上:

<star-with-label :label="value" :property="property" @sent-rating-in-parent="onClickChild">

要创建对象,请执行以下操作:{ 'property1': 'value1', 'property2': 'value2' ... }子级可以发出propertyvalue,并且您必须在父级中创建该对象。

也许是这样的:

/* child */

    setCurrentSelectedRating: function(rating) {
      this.$emit({ property: this.property, rating: this.rating }); // { property: bk_goodwill, rating: 4.76 }
    }
/* parent */

    data() {
      propertyRatings: {}
    },
    methods: {
      onClickChild({ property, rating }) {
        this.propertyRating[property] = rating

        console.log(this.propertyRating) // { bk_goodwill: 4.76 }
    }