首页 > 解决方案 > $refs 在 vue js 中返回 undefined

问题描述

我在使用ref标签的引用时遇到了困难,因为它当前返回null。部分代码如下所示:

<input-layout v-if="edit" label="Status" class="" ref="statusSubtitle">
        <u-select v-model='item.status' :options="adStatus" :disable="disable" tabindex="14" class="" ref="itemStatusDropDown"/>
</input-layout>

mounted () {
    this.$nextTick(function (){
      console.log("222 " + this.$refs.itemStatusDropDown)
      console.log("333 ", this.$refs.statusSubtitle)
    })
  },
computed: {
  edit () {
        //return true
        return this.item.getId() != null
      },
}

目前,钩子内的 console.logs mountedreturn undefined。这里的问题是edit()函数中的内容是异步的,因此在钩子被触发v-if="edit"时仍然是错误的。mounted我想为标签添加一个类属性<input-layout><u-select>因此我的思考过程是:

this.$refs.statusSubtitle.class.value = "makeItGray"
this.$refs.itemStatusDropDown.class.value = "makeItGray"

但是,因为this.$refs.statusSubtitlethis.$refs.itemStatusDropDown返回undefined我无法添加类属性。

在这种情况下,如何向类属性添加值?也许有一个我没有想到的解决方法?

注意:如果我强制edit()方法返回true,则ref不再是未定义的。但在这种情况下,该edit()方法正在执行异步任务。

标签: vue.jsasynchronous

解决方案


对于这种情况,我会观察edit计算结果。

Vue.config.devtools = false;
Vue.config.productionTip = false;

var app = new Vue({
  el: '#app',
  data: {
    status: false
  },
  computed: {
    edit() {
      return this.status;
    }
  },
  watch: {
    edit: {
      immediate: true,
      handler() {
        this.$nextTick(() => {
          if (this.$refs.myRef) {
            console.log(this.$refs.myRef);
            this.$refs.myRef.style.backgroundColor = 'green'
          }
        })
      }
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <button @click="status = !status">toggle</button>
  <p v-if="edit" ref="myRef">{{ edit }}</p>
</div>

https://vuejs.org/v2/guide/computed.html#Watchers


推荐阅读