0

I have custom function in my project which used as plugin

import Vue from 'vue'

function copyText(text) {
    var input = document.createElement('input');
    input.setAttribute('value', text);
    document.body.appendChild(input);
    input.select();
    var result = document.execCommand('copy');
    document.body.removeChild(input);
    return result;
}

Vue.prototype.$copyText = (text) => copyText(text);

How I can access to this vue prop inside asyncData?

3 Answers 3

1

Unfortunately you can't access this in asyncData as stated in the docs. However you could try to call the copy method in the mounted hook like this:

export default {
  mounted() {
    this.$copyText("some text");
  }
}
Sign up to request clarification or add additional context in comments.

Comments

0

You don't have access to the component instance through this inside asyncData because it is called before initiating the component.

Source: https://nuxtjs.org/api/

Comments

0

You can use inject in a plugin to get it in the asyncData instead the Vue prototype.

For example, in your plugin do this:

export default ({ app }, inject) => {
  inject('copyText', (text) => {
    const input = document.createElement('input')
    input.setAttribute('value', text)
    document.body.appendChild(input)
    input.select()
    const result = document.execCommand('copy')
    document.body.removeChild(input)
    return result
  })
}

and in the asyncData you can get it:

asyncDate({$http, $copyText}) {
  $copyText('text')
}

or in other place:

created() {
  this.$copyText('text')
}

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.