1

I'm having difficulty using the reference, ref, of a tag as it currently returns null. Parts of the code is shown below:

<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
      },
}

Currently the console.logs inside the mounted hook return undefined. The problem here is that what's in the edit() function is asynchronous, as a result the v-if="edit" is still false by the time the mounted hook gets triggered. I want to add a class property to the tags <input-layout> and <u-select> hence my thought process was to do:

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

However, since this.$refs.statusSubtitle and this.$refs.itemStatusDropDown return undefined I can't add the class properties.

How do I add a value to the class properties in this case? Maybe there is a work around that I'm not thinking of?

Note: If I force the edit() method to return true then ref is no longer undefined. But in this case, the edit() method is doing an asynchronous task.

1 Answer 1

2

For this case I would watch the edit computed.

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://v2.vuejs.org/v2/guide/computed.html#Watchers

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.