Andreas Hunter
Andreas Hunter

Reputation: 5014

How to access to custom Vue props inside asyncData in nuxtjs?

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?

Upvotes: 0

Views: 4156

Answers (3)

Jimmy Porto
Jimmy Porto

Reputation: 139

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')
}

Upvotes: 0

Szabó Csaba
Szabó Csaba

Reputation: 891

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/

Upvotes: 0

Troy Kessler
Troy Kessler

Reputation: 387

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");
  }
}

Upvotes: 1

Related Questions