vue 中 ref的一些常见作用

转:https://www.cnblogs.com/agen-su/p/11388621.html

复制代码
<template>
  <div>
    <!-- vue中的ref功能很强大,介绍一下如何使用的。基本用法:本页面获取dom元素。 -->
    <div id="app">
      <div ref="testDom">111</div>
      <button @click="getTest">获取test节点</button>
    </div>
  </div>
</template>

<script>
export default {
    methods:{
      getTest(){
        console.log(this.$refs.testDom);
      }
    }
}
</script>

<style>

</style>
复制代码

 

 


ref除了可以获取本页面的dom元素,还可以拿到子组件中的data和去调用子组件中的方法。

通过ref。父组件里面只要设置过ref的组件,都可以通过this.$refs[childeName]拿到子组件。

如果有两个子组件同时都叫 ref="abc"。那么 this.$refs.abc就是数组。如果只有一个,就是直接是那个子组件。


复制代码

<template>
  <div>
    <!-- ref除了可以获取本页面的dom元素,还可以拿到子组件中的data和去调用子组件中的方法。 -->
    <div id="app">
      <HelloWorld ref="hello"/>
      <button @click="getHello">获取helloworld组件中的值</button>
    </div>
  </div>
</template>

<script>
// 1.导入import组件。 2.声明组件。3.组件标签显示组件。
import { HelloWorld } from "./components/HelloWorld.vue";

export default {
  components:{HelloWorld},
  data(){
    return{}
  },
  methods:{
    getHello(){
      console.log(this.$refs.hello.msg)
    }
  },
}
</script>

<style>

</style>
复制代码

子组件:

复制代码
<template>
  <div>
    <!-- 子组件 -->
    {{msg}}
  </div>
</template>

<script>
export default {
  data(){
    return{
      msg:"hello world"
    }
  }
}
</script>

<style>

</style>
复制代码

 

 

 

 调用子组件中的方法:

子组件:

复制代码
<template>
<div>
  <!-- 子组件 -->
</div>
</template>

<script>
export default {
  methods:{
    open(){
      // 打印
      console.log("方法调用到了。");
    }
  }
}
</script>

<style></style>
复制代码

父组件

复制代码
<template>
  <div id="app">
    <HelloWorld ref="hello"/>
    <button @click="getHello">获取helloworld组件中的值</button>
  </div>
</template>

<script>
//1.导入子组件。2.声明子组件。3.组件标签。
import HelloWorld from "./components/HelloWorld.vue"; export default { components:{HelloWorld}, data(){return{}}, methods:{ getHello(){ this.$refs.hello.open(); }, } } </script> <style> </style>
复制代码

 

 

 子组件调用父组件的方法

子组件

复制代码
<template>
<!-- 这是子组件 -->
  <div></div>
</template>

<script>
export default {
  open(){
    console.log("调用了父组件中的方法。");
    // 调用了父组件中的方法  用this.$emit中写父组件的方法。
    this.$emit("refreshData");
  }
}
</script>

<style></style>
复制代码

父组件

复制代码
<template>
<!-- 这是父组件 -->
  <div id="app">
    <HelloWorld>
  </div>
</template>

<script>
import { HelloWorld } from "./components/HelloWorld.vue";
export default {
  components:{
    HelloWorld
  },
  data(){
    return{}
  },
  methods:{
    getHello(){
      this.$refs.hello.open()
    },
    getData(){
      console.log('11111');
    }
  }
}
</script>

<style>

</style>
复制代码

 

posted on   xiaoluoke  阅读(1888)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

导航

统计

点击右上角即可分享
微信分享提示