• A flower may bloom again, but a man is never young again
This $refs
  • This.$refs is an object that holds all DOM elements and child component instances of the current component that registered the REF feature

Note: $refs is populated only after the components have been rendered, they cannot be accessed during initial rendering, and it is non-responsive, so you cannot use it for data binding in templates

  • When ref and V-for are used together, the reference retrieved will be an array containing the source of the loop array
<template>
  <div>
    <div ref="myDiv" v-for="(item, index) in arr" :key="index">{{item}}</div>
  </div>
</template>
 
<script>
export default {
  data() {
    return {
      arr: ['one', 'two', 'three', 'four']
    }
  },
  mounted() {
    console.log(this.$refs.myDiv)
  },
  methods: {}
}
</script>
 
<style lang="sass" scoped>
 
</style>
 
Copy the code

Basic usage, this page gets dom elements
<template> <div id="app"> <div ref="testDom">11111</div> <script> export default { methods: { getTest() { console.log(this.$refs.testDom) } } }; </script>Copy the code

  • In addition to retrieving the DOM element of the page, ref can also retrieve data from the child component and call methods from the child component
Gets the data in the child component
  • Child components

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

<script>
export default {
  data() {
    return {
      msg: "hello world"
    }
  }
}
</script>
Copy the code
  • The parent component
<template> <div id="app"> < button@click ="getHello"> </div></template> <script> import HelloWorld from "./components/HelloWorld.vue"; export default { components: { HelloWorld }, data() { return {} }, methods: { getHello() { console.log(this.$refs.hello.msg) } } }; </script>Copy the code

Invoke methods in child components
  • Child components
<template> <div> </div></template> <script> export default {methods: {open() {console.log(" called ")}}} </script>Copy the code
  • The parent component
<template> <div id="app"> < button@click ="getHello"> </div></template> <script> import HelloWorld from "./components/HelloWorld.vue"; export default { components: { HelloWorld }, data() { return {} }, methods: { getHello() { this.$refs.hello.open(); }}}; </script>Copy the code

The child component calls the parent component method
  • Child components
<template> <div></div></template> <script> export default {methods: {open() {console.log(" called "); $emit("refreshData"); // Call the parent component method this.$emit("refreshData"); } } } </script>Copy the code
  • The parent component
<template> <div id="app"> <HelloWorld ref="hello" @refreshData="getData"/> <button @click="getHello"> </button> </div></template> <script> import helloWorld from "./components/HelloWorld.vue"; export default { components: { HelloWorld }, data() { return {} }, methods: { getHello() { this.$refs.hello.open() }, getData() { console.log('111111') } } }; </script>Copy the code