【问题标题】:How i can send data from child component to parent scrip section in Vue?如何将数据从子组件发送到 Vue 中的父脚本部分?
【发布时间】:2019-06-13 14:59:47
【问题描述】:

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

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

因此,我想在父组件中获取一个数组,如下所示: '属性1':'值1', “属性 2”:“值 2”

有人知道我该怎么做吗?

我的子组件

<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>

我的父组件代码:

import Vue from 'vue';
import StarsWithLabel from '../components/StarsWithLabel';
import VueResource from 'vue-resource';
Vue.use(VueResource);

export default {

  components: {
    'star-with-label': StarsWithLabel,
  },

  data: function () {
    return {
      config: window['endpointBookmakersProperties'],
      comment_content: null,
      showReview: false,
      showReviewForm: true,
      comment: null,
      comment_id: null,
      error_msg: '',
      showErrorMsg: false,
      pendingRatings: [],
    };
  },

  methods: {
    onSubmit: function () {
      const request = this.config['comment_url'];
      const requestRating = this.config['rating_url'];
      this.$http.post(
        request,
        {
          author_name: this.config['author_name'],
          author_email: this.config['author_email'],
          user_id: this.config['post_author'],
          author: this.config['post_author'],
          post: this.config['post'],
          content: this.comment_content,
        },
        {
          emulateJSON: true,
          headers: { 'X-WP-Nonce': this.config['nonce'] }
        }
      ).then(response => {
        // disable form
        this.showReviewForm = false;
        // show review
        this.showReview = true;
        // get comment id
        this.comment_id = response.body.id;

        // get body data
        console.log(response.body);
        // update bookmaker rating

      }, response => {
        // error callback
        this.showErrorMsg = true;
        this.error_msg = response.body.message;
      });
      if (this.comment_id !== 'undefined') {
        this.$http.post(
          requestRating,
          {
            user_id: this.config['post_author'],
            bookmaker_id: this.config['post'],
            properties_id: 'bk_goodwill',
            value: 5,
            comment_id: this.comment_id,
          },
          {
            emulateJSON: true,
            headers: { 'X-WP-Nonce': this.config['nonce'] }
          }
        ).then(response => {
          // get status
          console.log(response.status);

          // get status text
          console.log(response.statusText);

          // get body data
          console.log(response.body);

          // update bookmaker rating

        }, response => {
          // error callback
          this.showErrorMsg = true;
          this.error_msg = response.body.message;
        });
      }
    },
    onClickChild (value) {
      console.log(value);
    }
  },

};
</script>

<template>
    <div>

        <div v-if="showReview" class="current_user_review">
            <h3>Ваш отзыв:</h3>
            <div class="user-review">{{this.comment_content}}</div>
        </div>

        <div v-if="showErrorMsg">
            <h3>Произошла ошибка:</h3>
            <div class="error-review">{{this.error_msg}}</div>
        </div>

        <div v-if="showReviewForm">
            <h3>Оставить отзыв</h3>
            <div>
                <span @sent-rating-in-parent="onClickChild"></span>
            </div>
            <div class="add_reviews_form">
                <div class="bookmaker-ratings-items">
                    <div v-for="(value, property) in config['bookmaker_properties']" :key="property.id" class="rating-items" :id="property">
                        <star-with-label :label="value" :property="property"></star-with-label>
                    </div>
                </div>

                <form v-on:submit.prevent="onSubmit" class="new_review_form">
                  <textarea rows="8" cols="20" v-model="comment_content"></textarea>
                  <input type="submit" value="Отправить" class="btn btn-default btn-lg2 btn--is-s1">
                </form>
            </div>
        </div>

    </div>
</template>```

【问题讨论】:

  • 这个@sent-rating-in-parent="onClickChild"应该在&lt;star-with-label/&gt;标签中:&lt;star-with-label :label="value" :property="property" @sent-rating-in-parent="onClickChild"&gt;
  • 您好,谢谢!它工作正常,现在我在控制台中看到: 您已选择:bk_payments 4.49 颗星 您已选择:bk_payouts 4.54 颗星 您已选择:bk_goodwill 4.76 颗星 您已选择:bk_bettingrate 4.43 颗星,但我仍然不明白我是如何可以使数组像 'bk_payouts': '4.54', 'bk_goodwill' : '4.76' ?

标签: vue.js vue-component


【解决方案1】:

监听器属性的位置应该在子组件上:

<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 }
    }

【讨论】:

    猜你喜欢
    • 2018-09-04
    • 2021-02-15
    • 2017-09-13
    • 2017-07-25
    • 2019-04-11
    • 1970-01-01
    • 2020-09-28
    • 1970-01-01
    • 2018-03-07
    相关资源
    最近更新 更多