vue中的ref和$refs的使用


ref:被用來給元素或子組件注冊引用信息,引用信息將會注冊在父組件的$refs對象上。如果在普通的DOM元素上使用,那么指向的就是普通的DOM元素。

ref 有三種用法:

1、ref 加在普通的元素上,用this.ref.name 獲取到的是dom元素
2、ref 加在子組件上,用this.ref.name 獲取到的是組件實例,可以使用組件的所有方法。
3、如何利用 v-for 和 ref 獲取一組數組或者dom 節點


普通的DOM元素上使用

<div id="app7">
  <input type="text"ref="TEXT"/ >
  <button @click="add">添加</button>
</div>

var app7=new Vue({
  el:"#app7",
  data:{
 
  },
  methods:{
    add:function(){
      console.log(this.$refs);
    }
  }
})

  

子組件上使用

<div id="app7">
  <aaa ref=inputText></aaa>
  <input type="text"ref="TEXT" >
  <button @click="add">添加</button>
</div>
Vue.component('aaa',{
   template:"<div>我是一個組件</div>"
 })
 var app7=new Vue({
   el:"#app7",
   data:{
 
   },
   methods:{
     add:function(){
       console.log(this.$refs.inputText);
       console.log(this.$refs);
     }
   }
 })
 var aaa=app7.$refs.inputText;
 //console.log(aaa);
 //console.log(aaa.$el.innerText);

 refs:一個對象,持有注冊過 ref 特性 的所有 DOM 元素和組件實例 注意:

refs只會在組件渲染完成之后生效,並且它們不是響應式的。這只意味着一個直接的子組件封裝的“逃生艙”——你應該避免在模板或計算屬性中訪問 $refs

 

 

例:我做增刪改查, 模態框單獨分成了一個組件, 在父組件中如何調用子組件的 方法,而且傳數據到子組件,

一、首先先定義一個子組件,並引入

<listEditDialog ref="editDialog"></listEditDialog>
//這是父頁面,引用了listEditDialog 子組件 定義了一個ref屬性

 

二、假如我使用了一個表格, 里面有個修改的按鈕

 <el-table :data="tableData" border style="width: 100%">
        <el-table-column fixed prop="id" label="編號" width="150"></el-table-column>
        <el-table-column prop="title" label="標題" width="120"></el-table-column>
        <el-table-column label="圖片" width="120">
          <div slot-scope="scope" class="Img">
            <img :src="scope.row.bannerUrl" alt />
          </div>
        </el-table-column>
        <el-table-column prop="mark" label="備注" width="120"></el-table-column>
        <el-table-column prop="createTime" label="創建時間" width="300"></el-table-column>
        <el-table-column prop="sort" label="排序" width="120"></el-table-column>
        <el-table-column prop="status" label="狀態" width="120" :formatter="formStatus"></el-table-column>
        <el-table-column fixed="right" label="操作" width="100">
          <template slot-scope="scope">
            <el-button @click="editBefore(scope.row)" type="text" size="small">編輯</el-button>
            <el-button type="text" size="small" @click="deleteData(scope.row.id)">刪除</el-button>
          </template>
        </el-table-column>
      </el-table>

  

三、點擊編輯,調用子組件的方法,並且把這一行的數據傳給子組件

methods: {
    editBefore(row) {
      this.$refs.editDialog.edit(row);  //這里使用$refs  editDialog是上面定義的ref名字,  edit是子組件的方法名字    row是吧數據傳給子組件模態框。  這一句話就實現了父組件調用了子組件的方法並且傳了數據給子組件
} },

  

四、子頁面的代碼

methods: {
edit(row) {
      console.log(row)
      this.dialogFormVisible = true;
}
}

  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM