【问题标题】:Communicating between vue component and vue instancevue 组件和 vue 实例之间的通信
【发布时间】:2017-03-25 20:54:28
【问题描述】:

我刚刚开始使用 Vue.js,经过一段时间的尝试,我无法弄清楚如何将某些内容从组件传递到 vue 实例。 我将此组件用作评级系统,但我不明白如何将当前值获取到我的主实例 (https://fiddle.jshell.net/swyuarc9/)

Vue.component('star-rating', {

  props: {
    'name': String,
    'value': null,
    'id': String,
    'disabled': Boolean,
    'required': Boolean
  },

  template: '<div class="star-rating">\
        <label class="star-rating__star" v-for="rating in ratings" \
        :class="{\'is-selected\': ((value >= rating) && value != null), \'is-disabled\': disabled}" \
        v-on:click="set(rating)" v-on:mouseover="star_over(rating)" v-on:mouseout="star_out">\
        <input class="star-rating star-rating__checkbox" type="radio" :value="rating" :name="name" \
        v-model="value" :disabled="disabled">★</label></div>',

  /*
   * Initial state of the component's data.
   */
  data: function() {
    return {
      temp_value: null,
      ratings: [1, 2, 3, 4, 5]
    };
  },

  methods: {
    /*
     * Behaviour of the stars on mouseover.
     */
    star_over: function(index) {
      var self = this;

      if (!this.disabled) {
        this.temp_value = this.value;
        return this.value = index;
      }

    },

    /*
     * Behaviour of the stars on mouseout.
     */
    star_out: function() {
      var self = this;

      if (!this.disabled) {
        return this.value = this.temp_value;
      }
    },

    /*
     * Set the rating of the score
     */
    set: function(value) {
      var self = this;

      if (!this.disabled) {
        // Make some call to a Laravel API using Vue.Resource

        this.temp_value = value;
        return this.value = value;
      }
    }
  }

});

new Vue({
  el: '#app'
});

【问题讨论】:

    标签: javascript vue.js vue-component


    【解决方案1】:

    欢迎来到 Vue!

    一开始可能会有点困难,但传递属性的方式是通过props。为此,您需要首先在您的父级(在本例中为您的应用程序实例)上定义一个 data 对象。

    vue-docs 中有一些关于道具的好例子。
    一般来说,你是这样做的:

    new Vue({
      el: '#app',
      data: function () {
         return {
            foo: 'Foo'
         }
      }
    });
    
    Vue.component('bar', {
      props: { foo: String },
      template: '<span> {{ foo }}</span>'
    })
    

    ...和 ​​HTML

    <div id="app">
      <bar :foo="foo"></bar<
    </div>
    

    我分叉了你的小提琴并添加了一个演示道具,只是为了让你看到它的实际效果。 Check it out.

    【讨论】:

    • 你确定你链接的那个工作正常吗?如果我将鼠标悬停在星星上,什么也不会发生。
    • 我没有继续实施您的解决方案(甚至不确定它应该如何工作),我只是在其中添加了一个示例,展示了如何在组件之间共享数据。实施正确的行为取决于您:-)
    • 我可以通过使用 emit/on 来修复它。如果您想与子节点进行通信,我认为您的解决方案更合适。话虽如此,感谢您的帮助:)
    • 别担心,祝你好运!小心事件,如果你有太多事件,以后维护你的代码会变得非常困难:-)
    猜你喜欢
    • 2021-02-07
    • 1970-01-01
    • 2018-09-06
    • 2018-12-29
    • 2018-09-10
    • 2018-06-21
    • 2020-04-03
    • 2019-05-10
    • 2017-03-09
    相关资源
    最近更新 更多