1. 程式人生 > 程式設計 >Vue中ref的用法及演示

Vue中ref的用法及演示

目錄

    ref 定義:被用來給元素或子元件註冊引用資訊。引用資訊會被註冊在父元件上的$refs物件上。

    • 如果是在普通的dom元素上使用,引用指向的就是dom元素;
    • 如果用在子元件上,引用指向的就是元件例項。

    舉例:

    元件1:

    <template>
    
      <div>
    
          我是{
    
    {name}}
    
      </div>
    
    </template>
    
    <script>
    
    export default {  
    
        name:'Cpn1',data() {
    
            return {
    
                name:'元件1'
    
            }
    
        },}
    
    </script>

    元件2:

    <template>
    
      <div>我是{
    
    {name}}</div>
    
    </template>
    
    <script>
    
    export default { 
    
        name:'Cpn2',data() {
    
            return { 
    
                name:'元件2'
    
            }
    
        },}
    
    </script>

    App.

    <template>
    
      <div id="app">
    
        <cpn-1 ref="c1"></cpn-1>
    
        <cpn-2 ref="c2"></cpn-2>
    
        <button @click="showDom">按鈕</button>
    
        <h2 r客棧
    ef="title">我是標題</h2> <input type="text" ref="input" value="123"> </div> </template> <script> import Cpn1 from "./components/Cpn1.vue"; import Cpn2 from "./components/Cpn2.vuehttp://www.cppcns.com"; export default { components: { Cpn1,Cpn2 },name: "App",methods: { showDom() { console.log(this.$refs.c1); console.log(this.$ref
    s.c2.$data.name); console.log(this.$refs.title) console.log(this.$refs.input.value) // 獲取一個真實的dom物件並修改值 var title=this.$refs.title; title.innerText="helloWord" },},}; </script>

    執行上面的程式,點選頁面上的《按鈕》,效果如下:

    Vue中ref的用法及演示

    同時看控制檯:

    Vue中ref的用法及演示

    可以看到當ref物件用在普通元素上時獲取到的是普通DOM元素,當ref用在子元件上時,引用指向元件例項。

    根據實際需要,可以通過ref給元素或者子元件註冊引用資訊,在需要用到的時候我們可以通過$refs獲取真實的DOM元素或者元件例項進行我們想要的操作。

    到此這篇關於Vue中ref的用法及演示的文章就介紹到這了,更多相關Vue中ref的用法內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!