Vue2 中 ref 用法示例

本文详细介绍了Vue.js中组件之间的通信方法,包括使用`$refs`获取子组件实例、父组件获取子组件数据、父组件调用子组件方法以及子组件如何触发父组件方法。同时,通过实例展示了如何避免直接操作DOM,利用Vue的响应式系统进行数据交互,提升应用性能。


一般情况下需要获取dom元素中的值需要如下代码处理:

<!DOCTYPE html>
<html>
  
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title></title>
    
    <script type="text/javascript">
      function getUser() {
        let data = document.querySelector(".user").value;
        alert(data);
      }
      
      function getPwd() {
        let data = document.getElementById("pwd").value;
        alert(data);
      }
    </script>
  </head>
  
  <body>
    <input class="user" type="text" name="username">
    <input id="pwd" type="text" name="password">
    <button onclick="getUser()">获取User</button>
    <button onclick="getPwd()">获取Pwd</button>
  </body>
  
</html>

1、基本用法

<template>
<div>
  <div ref="basicRef">hello world</div>
  <button @click="getDom">点击获取</button>
  </div>
</template>

<script>
  export default {
    methods: {
      getDom() {
        console.log(this.$refs.basicRef);
      },
    },
  };
</script>

点击输出:<div>hello world</div>

2、父组件获取子组件数据

<template>
  <div>
    {{msg}}
  </div>
</template>

<script>
export default {
  data() {
    return {
      msg: "child component",
    };
  },
};
</script>
<template>
  <div>
    <ChildRefSample ref="childRef" />
    <button @click="getChildData">获取子组件数据</button>
  </div>
</template>

<script>
import ChildRefSample from "./ChildRefSample.vue";
export default {
  components: {
    ChildRefSample,
  },
  methods: {
    getChildData() {
      console.log("getChildData: ", this.$refs.childRef.msg);
    },
  },
};
</script>

点击输出:getChildData: child component

3、父组件调用子组件方法

<template>
  <div>
  </div>
</template>

<script>
export default {
  methods: {
    hello() {
      console.log("hello");
    },
  },
};
</script>
<template>
  <div>
    <ChildRefSample ref="childRef" />
    <button @click="getChildData">获取子组件数据</button>
  </div>
</template>

<script>
import ChildRefSample from "./ChildRefSample.vue";
export default {
  components: {
    ChildRefSample,
  },
  methods: {
    getChildData() {
      this.$refs.childRef.hello()
    },
  },
};
</script>

输出:hello

4、子组件调用父组件方法

<template>
  <div></div>
</template>
<script>
export default {
  methods: {
    hello() {
      this.$emit("callParent");
    },
  },
};
</script>
<template>
  <div>
    <ChildRefSample
      ref="childRef"
      @callParent="printData"
    />
    <button @click="getChildData">获取子组件数据</button>
  </div>
</template>

<script>
import ChildRefSample from "./ChildRefSample.vue";
export default {
  components: {
    ChildRefSample,
  },
  methods: {
    getChildData() {
      this.$refs.childRef.hello();
    },
    printData() {
      console.log("print parent data");
    },
  },
};
</script>

输出:print parent data

PS:最新在学前端,以下是学习过程中写的一个小程序,欢迎体验~

### Vue 2 中 `ref` 和 `$refs` 的具体用法及区别 在 Vue 2 中,`ref` 和 `$refs` 是两个重要的特性,用于直接访问 DOM 元素或子组件实例。以下是它们的具体用法和区别。 #### 1. `ref` 的用法 `ref` 是一个特殊属性,可以绑定到元素或子组件上,为该元素或组件赋予一个引用名称。当绑定到普通 DOM 元素时,`ref` 返回的是该 DOM 元素;当绑定到子组件时,返回的是子组件的实例。 ```html <template> <div> <!-- 绑定到普通 DOM 元素 --> <p ref="paragraph">Hello World</p> <!-- 绑定到子组件 --> <ChildComponent ref="child" /> </div> </template> ``` 在上述代码中,`ref="paragraph"` 为 `<p>` 元素赋予了一个引用名称,而 `ref="child"` 则为 `ChildComponent` 子组件赋予了引用名称[^2]。 #### 2. `$refs` 的用法 `$refs` 是 Vue 实例的一个属性,它是一个对象,包含了所有通过 `ref` 注册的 DOM 元素或子组件实例。需要注意的是,`$refs` 只有在组件渲染完成后才会被填充,因此不能在初始渲染时访问它们[^4]。 以下是一个示例: ```javascript export default { mounted() { // 访问普通 DOM 元素 console.log(this.$refs.paragraph); // 输出: <p>HTML 元素</p> // 访问子组件实例 console.log(this.$refs.child); // 输出: 子组件的实例 } }; ``` #### 3. 区别与注意事项 - **响应性**:`$refs` 是非响应式的,因此不建议在模板中使用它进行数据绑定[^5]。 - **注册时间**:由于 `ref` 是在渲染结果中创建的,因此在组件的生命周期钩子中(如 `mounted`),才能安全地访问 `$refs`[^4]。 - **结合 `v-for` 使用**:如果将 `ref` 与 `v-for` 结合使用,那么 `$refs` 中对应的值将是一个数组,包含所有的 DOM 节点或组件实例。 ```html <template> <div> <div v-for="(item, index) in items" :key="index" ref="itemRefs"> {{ item }} </div> </div> </template> <script> export default { data() { return { items: [&#39;A&#39;, &#39;B&#39;, &#39;C&#39;] }; }, mounted() { console.log(this.$refs.itemRefs); // 输出: [div, div, div] } }; </script> ``` #### 4. 总结 - 在 Vue 2 中,`ref` 用于为 DOM 元素或子组件赋予引用名称。 - `$refs` 是 Vue 实例的一个属性,用于访问所有通过 `ref` 注册的 DOM 元素或子组件实例。 - `$refs` 是非响应式的,且只有在组件渲染完成后才能访问[^2]。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值