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 2022-11-11 16:19  xiaoluoke  阅读(1733)  评论(0编辑  收藏  举报

导航