vuejs -为什么“this.$refs.variable”给出undefined,但当我使用“variable”的值时,它工作[重复]

ckocjqey  于 2023-03-24  发布在  Vue.js
关注(0)|答案(1)|浏览(167)

此问题在此处已有答案

(19个答案)
4天前关闭。
我对vue.js有点陌生,但仍然......我不明白它的行为。有人能解释一下为什么当我在“this.$refs.somevariable"之后使用变量时,我会得到一个undefined result,但如果我使用变量的值,那么它就可以工作了?

<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>
gzszwxb4

gzszwxb41#

试试下面的代码段:(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>

相关问题