vue中ref的用法

ref

  1. 预期:string

    ref 被用来给元素或子组件注册引用信息。引用信息将会注册在父组件的 $refs 对象上。

  2. 如果在普通的 DOM 元素上使用,引用指向的就是 DOM 元素;

  3. 如果用在子组件上,引用就指向组件实例:

    <!-- `vm.$refs.p` will be the DOM node -->
    <p ref="p">hello</p>
    
    <!-- `vm.$refs.child` will be the child component instance -->
    <child-component ref="child"></child-component>

    当 v-for 用于元素或组件的时候,引用信息将是包含 DOM 节点或组件实例的数组。

    关于 ref 注册时间的重要说明:因为 ref 本身是作为渲染结果被创建的,在初始渲染的时候你不能访问它们 - 它们还不存在!$refs 也不是响应式的,因此你不应该试图用它在模板中做数据绑定。

     

 通过官方的说明,其实ref就是一个引用。

 

 

 

上图中,有三处有ref

1)helloRef是一个组件里的,这个组件就是初创项目的时候显示的一个字符串

2)yearInput是一个element-ui的一个文本框,用于输入一个值

3)tableRef是一个element-ui的一个表格

 

 

getTableColumns是一个测试的method

第一行显示的是一个字符串

第二行显示的是输入的值

第三行显示的是一个表格的数据

 

<template>
  <div>
    <hello-world ref="helloRef"></hello-world>
    <el-input
      v-model="xs_year"
      placeholder="请输入内容"
      @blur="inputChange"
      ref="yearInput"
    ></el-input>
    <el-table :data="tableData" ref="tableRef">
      <el-table-column prop="xs_year" label="日期" width="140">
      </el-table-column>
      <el-table-column prop="realname" label="姓名" width="120">
      </el-table-column>
      <el-table-column prop="xq_code" label="地址"> </el-table-column>
    </el-table>
  </div>
</template>

<script>
import { getXsList } from '../api/index'
import Pagination from "../components/pagination";
import Progress from "../components/progress";
import HelloWorld from '../components/HelloWorld';

export default {
  name: "UserList",
  components: { Pagination, Progress, HelloWorld },
  data () {
    return {
      xs_year: '2018',
      pageR: {
        page: this.$page,
        size: this.$size
      },
      tableData: null
    }
  },
  created () {
  },
  mounted () {
    let _this = this;
    _this.getXsList(this.xs_year, null, null);
  },

  destroyed () {
  },
  methods: {
    inputChange () {
      this.getTableColumns();
    },
    getTableColumns () {
      console.log(this.$refs.helloRef.msg)
      console.log(this.$refs.yearInput.value)
      console.log(this.$refs.tableRef.data)
    },
    getXsList (xs_year, xq_code, realname) {
      this.loading = true;
      const params = {
        xs_year: xs_year,
        xq_code: xq_code,
        realname: realname
      };
      console.log(JSON.stringify(params));
      getXsList(params).then((res) => {
        if (res.data) {
          let r = res.data;
          this.tableData = r.rows;
        } else {
          this.showErrMsg('请求错误!');
        }
        this.loading = false;
      }).catch(() => {
        this.showErrMsg('请求错误!');
        this.loading = false;
      });
    }
  }

}
</script>
<style scoped>
</style>

 

posted @ 2021-03-09 20:26  jiduoduo  阅读(8722)  评论(0编辑  收藏  举报