简体   繁体   English

如何在 nuxtjs 中访问 asyncData 中的自定义 Vue 道具?

[英]How to access to custom Vue props inside asyncData in nuxtjs?

I have custom function in my project which used as plugin我的项目中有自定义 function 用作插件

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 ?我如何在asyncData中访问这个 vue 道具?

Unfortunately you can't access this in asyncData as stated in the docs .不幸的是,您无法按照文档中的说明在 asyncData 中访问 However you could try to call the copy method in the mounted hook like this:但是,您可以尝试在挂载钩子中调用 copy 方法,如下所示:

export default {
  mounted() {
    this.$copyText("some text");
  }
}

You don't have access to the component instance through this inside asyncData because it is called before initiating the component.不必通过访问组件实例this里面asyncData ,因为它正在启动组件之前调用。

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

You can use inject in a plugin to get it in the asyncData instead the Vue prototype.您可以在plugin使用inject以将其放入asyncData而不是 Vue 原型中。

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:asyncData你可以得到它:

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

or in other place:或在其他地方:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM