Search code examples
vue.jsvuejs3refs

vuejs - why "this.$refs.variable" gives undefined, but when I use the value of the "variable" it works


I'm a bit new with vue.js but still...I don't understand the behavior. Could someone explain why when I use a variable after "this.$refs.somevariable", I have an undefined result, but if I use the value of the variable, then it works ?:

<script>

export default {
    
  mounted() {
    //
  },

  methods: {

      scrollTo: function(anchor) {

        console.log(anchor); // "whoAreWe"
        console.log(this.$refs.anchor); // Undefined
        console.log(this.$refs.whoAreWe); //the DOM div "whoAreWe"
      
      }

    },

};
</script>

<template>
   ...
<button
    type = "button"
    @click = scrollTo('whoAreWe')>
    **Click!**
</button>  
...
<div ref="whoAreWe">
<div>
</template>

Solution

  • Try like following snippet: (this.$refs[anchor])

    const app = Vue.createApp({
      methods: {
        scrollTo: function(anchor) {
          console.log(anchor); 
          console.log(this.$refs[anchor]); 
          console.log(this.$refs.whoAreWe); 
        }
      },
    })
    app.mount('#demo')
    <script src="https://unpkg.com/vue@3/dist/vue.global.prod.js"></script>
    <div id="demo">
      <button
        type = "button"
        @click = scrollTo('whoAreWe')>
        **Click!**
      </button> 
      <div ref="whoAreWe">
      <div>
    </div>