$refs的用法

553 阅读1分钟

$refs的基本用法

ref有三种用法

  • ref加在普通元素上,用this.$refs.(ref值)获取到的是dom元素;
  • ref加在子元素上,用this.refs.(ref值)获取到的是组件实例,可以使用组件的所有方法,在使用方法的时候直接this.$refs.(ref值)。方法()就可以使用了;
  • 我感觉上面讲的都是一些废话,说了跟没说一样,还是没看懂,还是要结合实例来分析,谁是谁?

先看例子,我们再总结ref的功能

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

<script>
new Vue({
   el:"#app",
   methods:{
   add:function(){
   this.$refs.input1.value = "22";//先获取这个节点,然后再给它赋值value
   
   }
   }
})
</script>

-一般来讲,获取DOM元素,需document.querySelector(".input1")获取这个dom节点,然后在获取input1的值。

但是用ref绑定之后,我们就不需要在获取dom节点了,直接在上面的input上绑定input1,然后$refs里面调用就行。

  • ref的功能就是获取DOM节点,优点是直接在this.$refs.input1 调用就可以了,减少普通方式获取dom节点的消耗;
  • 普通方式获取dom节点的方式document.querySelector(".input1")

el-upload

  • el-upload是elementUi里面的一个组件,可以直接拿来用;
  • 此处实例用的是拖拽上传;

image.png

  • elementUi的样式;

image.png

本实例中ref的用法

  • <el-upload>上绑定了ref;
 <el-upload ref="upload" :on-success="handleFileSuccess"  ></el-upload>
 

el-upload本身的属性

methods

  • 方法名:submit,是手动上传文件列表;

  • 方法名:clearFiles,清空已上传的文件列表;

  • 实例中的methods如何用到的el-upload的方法;

    • 当点击确定按钮时,上传文件列表;
  <div slot="footer" class="dialog-footer">
  <el-button type="primary" @click="submitFileForm">确 定</el-button>
  <el-button @click="upload.open = false">取 消</el-button>   </div>
  
   // 提交上传文件
   methods:{
    submitFileForm() {
    this.$refs.upload.submit();
            },
       }

image.png

文件上传成功后

  • 文件上传成功后,会调用on-success后面的。文件上传成功后的钩子函数handleFileSuccess; -钩子函数为:
    //  文件上传成功处理
            handleFileSuccess(response, file, fileList) {
                this.upload.open = false;
                this.upload.isUploading = false;
                this.$refs.upload.clearFiles();
                this.$alert(
                    "<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" +
                    response.msg +
                    "</div>",
                    "导入结果", {
                        dangerouslyUseHTMLString: true
                    }
                );

  • 在里面处理了UOLoading