在线观看不卡亚洲电影_亚洲妓女99综合网_91青青青亚洲娱乐在线观看_日韩无码高清综合久久

鍍金池/ 問答/HTML/ Vue.js 如何獲取子組件中的任意元素

Vue.js 如何獲取子組件中的任意元素

圖片描述

如圖,動態(tài)添加節(jié)點為一行文字和對應(yīng)的input,input原本是隱藏的,點擊文字之后顯示input。之后我想讓input獲得焦點(focus),但不知該如何恰當?shù)墨@取這個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 組件內(nèi) input 的 ref 嘛。
兩種方法:
1、test 組件內(nèi):直接拿 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()
            })
        }
2017年11月7日 07:42
編輯回答
遺莣

你輸出或者獲取refs的時候那個虛擬dom渲染成功了么, 要在渲染后再獲取, $nexttick了解一下

2017年4月27日 10:10