当前位置:   article > 正文

vue ref和$refs 获取元素dom、获取子组件数据与方法_vue ref获取元素

vue ref获取元素
作用

        ref和$refs配合使用可以用于获取DOM元素或组件实例

特点

        查找范围在当前组件内,更精确稳定,范围更小

使用
获取DOM

        (1)在目标标签添加ref属性

<div ref="demo">测试测试</div>

        (2)获取DOM

        通过this.$refs.xxx获取,获取到了还可更改此元素样式等

const demoDom =  this.$refs.demo;
获取子组件实例

          (1)在子组件标签添加ref属性

<Son ref="sonRef"></Son>

        (2)获取子组件实例

        也是通过this.$refs.xxx获取,获取到了即可拿到子组件的数据和方法

const sonDom = this.$refs.sonRef;
完整例子

        父组件代码(含vue3写法喔)

  1. <template>
  2. <div>
  3. <div ref="demo">测试测试</div>
  4. <h1 style="color: red;" :onclick="getDemo">点击获取demo</h1>
  5. <h1 style="color: red;margin-top: 50px;" @click="getSonRef">点击获取子组件实例</h1>
  6. <Son ref="sonRef"></Son>
  7. <div v-if="sonData.das">
  8. <p>{{ sonData.das }}</p>
  9. <botton @click="sonData.fun">调用子组件方法</botton>
  10. </div>
  11. </div>
  12. </template>
  13. <script>
  14. import Son from './son.vue'
  15. export default {
  16. components: {
  17. Son
  18. },
  19. data() {
  20. return {
  21. sonData: {}
  22. }
  23. },
  24. methods: {
  25. getDemo() {
  26. const demoDom = this.$refs.demo;
  27. console.log('获取到的demo的Dom数据是===', demoDom);
  28. },
  29. getSonRef() {
  30. const sonDom = this.$refs.sonRef;
  31. this.sonData = sonDom;
  32. console.log('获取到的子组件的实例是===', sonDom);
  33. }
  34. }
  35. }
  36. </script>
  37. <!-- vue3的写法 -->
  38. <!-- <script setup>
  39. import Son from './son.vue'
  40. import { ref } from 'vue'
  41. // 声明同名的ref变量即已经去获取了对应的dom或实例,相当于执行了this.$refs.xxx
  42. let demo = ref()
  43. let sonRef = ref()
  44. const getDemo = () => {
  45. console.log('获取到的demo的Dom数据是===', demo);
  46. }
  47. const getSonRef = () => {
  48. console.log('获取到的子组件的实例是===', sonRef);
  49. }
  50. </script> -->

        子组件代码

  1. <template>
  2. <div>子组件</div>
  3. </template>
  4. <script>
  5. export default {
  6. data() {
  7. return {
  8. das: '我是子组件数据呀'
  9. }
  10. },
  11. methods: {
  12. fun() {
  13. console.log('我是子组件方法呀');
  14. }
  15. }
  16. }
  17. </script>

        效果

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/运维做开发/article/detail/741169
推荐阅读
相关标签
  

闽ICP备14008679号