Vue.js 如何获取子组件中的任意元素

图片描述

如图,动态添加节点为一行文字和对应的input,input原本是隐藏的,点击文字之后显示input。之后我想让input获得焦点(focus),但不知该如何恰当的获取这个input(不使用DOM操作)。

代码如下:(html文件)

<script src="https://cdn.jsdelivr.net/npm/vue"></script>
<div id="app">
        <test v-for="(item,index) in items" :item="item" @show="show"></test>
</div>
<script>
Vue.component('test',{
    props:['item'],
    template:
    `
    <div>
        <p @click="show($event,item)">{{item.text1}}</p>
        <input v-model="item.text1" v-show="item.show_input" :ref="item.text1"></input>
    </div>
    `,
    methods:{
        show(event,item){
            this.$emit('show',event,item);
        }
    }
});
new Vue({
    el:'#app',
    data:{
        items:[
            {
                'text1':'aaaaaaa',
                'show_input':false
            },
            {
                'text1':'bbbbbbb',
                'show_input':false
            }
        ]
    },
    methods:{
        show(event,item){
            item.show_input=true;
            let ref_name=item.text1;
            console.log(this.$refs.ref_name); // undefined

        }
    }
});
</script>
阅读 23.1k
2 个回答

你在组件外凭什么能直接拿到你 test 组件内 input 的 ref 嘛。
两种方法:
1、test 组件内:直接拿 input 的 ref。

        show(event,item){
            this.$emit('show',event,item);
            console.log(this.$refs[item.text1]);
            this.$nextTick(() => {
              this.$refs[item.text1].focus()
            })
        }

2、外部组件:先拿到 test 组件的 ref,再拿 input 的 ref。

        show(event,item){
          console.log(this.$refs)
            item.show_input = true;
            this.$nextTick(() => {
              // 
              this.$refs[`test-${item.text1}`][0].$refs['input'].focus()
            })
        }

你输出或者获取refs的时候那个虚拟dom渲染成功了么, 要在渲染后再获取, $nexttick了解一下

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