【问题标题】:How to access to custom Vue props inside asyncData in nuxtjs?如何在 nuxtjs 中访问 asyncData 中的自定义 Vue 道具?
【发布时间】:2023-03-21 20:24:02
【问题描述】:

我的项目中有自定义函数用作插件

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

如何在asyncData 中访问这个 vue prop?

【问题讨论】:

    标签: javascript vue.js vuejs2 nuxt.js


    【解决方案1】:

    不幸的是,您无法在 asyncData 中访问 this,如 docs 中所述。但是,您可以尝试像这样在挂载的钩子中调用复制方法:

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

    【讨论】:

      【解决方案2】:

      无权通过asyncData 内的this 访问组件实例,因为它是在在启动组件之前调用的。

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

      【讨论】:

        【解决方案3】:

        您可以在 plugin 中使用 injectasyncData 而不是 Vue 原型中获取它。

        例如,在您的插件中执行以下操作:

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

        asyncData你可以得到它:

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

        或在其他地方:

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

        【讨论】:

          猜你喜欢
          • 2019-02-02
          • 2020-08-17
          • 2021-09-23
          • 2021-06-18
          • 2019-11-28
          • 2021-10-25
          • 1970-01-01
          • 2021-07-17
          • 2017-06-05
          相关资源
          最近更新 更多