如图,动态添加节点为一行文字和对应的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>
你在组件外凭什么能直接拿到你 test 组件内 input 的 ref 嘛。
两种方法:
1、test 组件内:直接拿 input 的 ref。
2、外部组件:先拿到 test 组件的 ref,再拿 input 的 ref。