1

我使用$refs绑定子组件但无法从父组件彻底获取子组件的值$ref.refname.msg。(我试过$children哪个可以工作)。

  1. 已定义子组件的味精。

  2. 味精信息可以通过parent.$chidren.msg

但错误表明:

未捕获的类型错误:无法读取未定义的属性“msg”。

这是 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'
    });

JSFaddle 中的代码

4

1 回答 1

3

您应该放置ref="xx"子组件,而不是模板。

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

模板只是模板,父组件不能引用它们。

这里是官方的使用文档refhttps ://vuejs.org/v2/guide/components.html#Child-Component-Refs

于 2017-01-16T09:35:16.977 回答