2017-01-16 11 views
0

Я использую $refs, чтобы связать дочерний компонент, но не могу получить значение дочернего компонента из исходного компонента $ref.refname.msg. (Я пробовал $children, который мог бы работать).

  1. msg Детский компонент был определен.

  2. Мгновенная информация может быть получена через parent.$chidren.msg.

Но ошибка показала, что:

Uncaught TypeError: Cannot read property 'msg' of undefined.

Вот HTML-код.

 <template id="parent-component" ref='parent'> 
     <div> 
     <child-component1></child-component1> 
     <child-component2></child-component2> 
     <button v-on:click="showChildData">Show child component data</button> 
     </div> 
     </template> 

     <template id="child-component1" ref="cc1"> 
     <div> 
      <span> This is child component 1.</span> 
      <button v-on:click="showParentData">Show parent component data</button> 
     </div> 
     </template> 

     <template id="child-component2" ref="cc2"> 
     <div> 
      <span> This is child component 2.</span> 
      <button v-on:click="showParentData">Show parent component data</button> 
     </div> 
     </template> 

     <div id="e15"> 
     <parent-component></parent-component> 
     </div> 

Вот JavaScript:

Vue.component('parent-component',{ 
     template: '#parent-component', 
     components: { 
      'child-component1': { 
       template: '#child-component1', 
       data: function(){ 
        return { 
         msg: 'This is data of cc1' 
        }; 
       }, 
       methods: { 
        showParentData: function(){ 
         alert(this.$parent.msg); 
        } 
       } 
      }, 
      'child-component2': { 
       template: '#child-component2', 
       data: function() { 
        return { 
         msg: 'This is data of cc2', 
         num: 12 
        }; 
       }, 
       methods: { 
        showParentData: function(){ 
         alert(this.$parent.msg); 
        } 
       } 
      } 
     }, 
     data: function() { 
      return { 
       msg: 'This is data of parent.' 
      }; 
     }, 
     methods: { 
      showChildData: function(){ 


       for(var i=0;i<this.$children.length;i++){ 
        alert(this.$children[i].msg); 
        // console.log(this.$children[i]); 
       } 
       //!!!!This line doesn't work!!! 
       alert(this.$refs.cc2.msg); 

      } 
     } 
    }); 


    var e15 = new Vue({ 
     el: '#e15' 
    }); 

Code in JSFaddle

ответ

1

Вы должны положить ref="xx" на дочерних компонентов, а не шаблоны.

<child-component1 ref="cc1"></child-component1> 
<child-component2 ref="cc2"></child-component2> 

Шаблоны - это просто шаблоны, родительский компонент не может их возвращать.

Вот официальный документ для использования ref: https://vuejs.org/v2/guide/components.html#Child-Component-Refs

+0

Проблема решена. Большое спасибо!! –

+0

@YaoIris, пожалуйста, отметьте этот ответ как «принятый», если он решает проблему –