---
# System prepended metadata

title: ref 操作DOM元素技巧 (5-1)
tags: [5. 進階Api, Vue]

---

# ref 操作DOM元素技巧 (5-1)
###### tags: `Vue`、`5. 進階Api`
2022.3.7

&emsp;&emsp;「ref」可以加在標籤中，讓Vue可以隨時藉此連結到標籤，並對其做動作。


### 範例1：點擊按鈕，馬上關注 ref 所標得input
```
<input type="text" ref="inputDom"></br>
<button @click="mounted">使用ref focuse</button>

<script>

        const app = Vue.createApp({
            data(){
                return{
                    test:'ref動作，關注此輸入框'
                }
            },
            methods:{
                mounted(){
                    this.$refs.inputDom.focus();
                }
            }
        });


        app.mount('#app');

</script>
    

```
### 範例2：使用 ref 取得元件內的資訊
```
<h1><button @click="change_component_data">更改資料</button></h1>
<oldmoon ref="dom_oldmoon"></oldmoon>

<script>
    const app = Vue.createApp({
        data(){
                return{
                    test:'跟改元件內資料'
                }
        },
        methods:{
            change_component_data(){
                    this.$refs.dom_oldmoon.title = '這是「更改後」標題'
            }
        }
    });

    app.component('oldmoon',{
        data(){
                return{
                    title:'這是「原本」標題',
                    content:'這是內容'
                }
        },
        template:
            `<h1>{{ title }}</h1>
            <h2>{{ content }}</h2>`
        });

        app.mount('#app');

</script>
```

### 範例三：使用 ref 控制boostrap modal
```

<button class="btn btn-primary" @click="open_modal">開啟bootstrap modal</button>

<!-- bootstrap modal(跳出框) -->
<div class="modal" tabindex="-1" ref="ref_modal">
    <div class="modal-dialog">
      <div class="modal-content">
        <div class="modal-header">
          <h5 class="modal-title">Modal title</h5>
            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <p>Modal body text goes here.</p>
                </div>
           <div class="modal-footer">
               <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
               <button type="button" class="btn btn-primary">Save changes</button>
           </div>
        </div>
    </div>
</div>
<!------------------------>

const app = Vue.createApp({
    data(){
            return{
                bsModal:''
                
            }
    },
    
    methods:{   
            open_modal(){
                    this.bsModal.show()
            }
    },
    
    mounted(){
            this.bsModal = new bootstrap.Modal(this.$refs.ref_modal)
    }
});

app.mount('#app');

```