vue自定义组件ref报错

在使用自定义组件使用ref的时候,发现会报错,
当正确的时候:点击按钮输入框focus

 <div id="L4">
                <ref-component>
                </ref-component>
                
           </div>
           <script>
            Vue.component('ref-component',{
              template:`
                        <div>
                           <input ref="name" type="text">
                            <button  @click="focus">fouce</button>
                        </div>
                       `,
              methods:{
                focus:function(){
                this.$refs.name.focus()
                }
              }
            })
            new Vue({
              el:'#L4'
            })

但是将输入框写入一个子组件的时候再执行按钮事件,就会报错

     <div id="L4">
                <ref-component>
                </ref-component>
                
           </div>
           <script>
            Vue.component('ref-component',{
              template:`
                        <div>
                           <refs-component ref="name"></refs-component>
                            <button  @click="focus">fouce</button>
                        </div>
                       `,
              methods:{
                focus:function(){
                this.$refs.name.focus()
                }
              }
            })
            Vue.component('refs-component',{
              template:`<input type="text" />`
            })
            new Vue({
              el:'#L4'
            })
           </script>

报错是

clipboard.png

请问如何才能访问这个子组件的内容呢?

阅读 5.1k
1 个回答

显然是refs-component这个组件没有focus方法,你没有引用在input上

Vue.component('refs-component',{
  template:`<input ref='input' type="text" />`,
  methods: {
     focus(){
         this.$refs.input.focus();
     }
  }    
})

这样试试

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题