如何使子组件了解Vue中的嵌套初始化数据?

时间:2019-05-27 16:21:48

标签: javascript vue.js

所以,这是我的测试代码:

Vue.component('area-selectors-box', {
  template: `
    <div class="selectors-box">
      <area-selector v-for="select in selects"></area-selector>
    </div>
  `,
  props:['selects']
});

Vue.component('area-selector', {
  template: `
    <select>
      <option disabled selected value="">Seleziona continente</option>
      <option :areas="select.areas" v-for="area in areas">{{ area.name }}</option>
    </select>
  `,
  props:['select']
});

var dealer_manager = new Vue({
  el: '#dealers-main-box'
  ,data:{
    dealers:[],
    selects:[]
  }
  ,mounted: function(){
  }
  ,created: function(){
    this.get_dealers_data('00');
  }
  ,methods: {
    get_dealers_data: function(area_id){
      var app = this;

      $.ajax({
        type: 'GET'
        ,dataType: 'json'
        ,url: dealers_settings.api_url + area_id
      })
      .done(function(json_data, status, xhr){
        if(!json_data) return;
        var parsed = JSON.parse(json_data);
        if(parsed.type == 'areas'){
          app.selects.push({
            areas: parsed.items
          });
        } else if(parsed.type == 'dealers'){
          app.dealers = parsed.items;
        }
      }.bind(this))
      .fail(function( jqXHR, textStatus, errorThrown ){
      }.bind(this))
    }// get dealers data
  }
});

这是我获取并传递到area-selectors-box的json数据:

enter image description here

好。但是区域选择器中的数据为空。在初始化过程中如何使它知道区域?如您所见,区域是对象的数组。

enter image description here

(对我而言)足够奇怪,如果我在一个组件中全部完成,它将正常工作:

Vue.component('area-selectors-box', {
  template: `
    <div class="selectors-box">
      <select :selects="selects" v-for="select in selects">
        <option disabled selected value="">Seleziona continente</option>
        <option v-for="area in select.areas">{{area.name}}</option>
      </select>
    </div>
  `,
  props:['selects']
});

所以我想我应该学习的是如何将子数据传递给子组件...有什么帮助吗? :)

1 个答案:

答案 0 :(得分:0)

解决:我必须通过任何事情。

Vue.component('area-selectors-box', {
  template: `
    <div class="selectors-box">
      <area-selector v-for="select in selects" :select="select"></area-selector>
    </div>
  `,
  props:['selects']
});

Vue.component('area-selector', {
  template: `
    <select :select="select">
      <option disabled selected value="">Seleziona continente</option>
      <area-option v-for="area in select.areas" :area="area" :key="area.term_id"></area-option>
    </select>
  `,
  props:['select']
});

Vue.component('area-option', {
  template: `<option :area="area">{{area.name}}<slot></slot></option>`
  ,props: ['area']
});