如何使用nuxt js将自己的js用作插件

时间:2017-10-18 08:06:22

标签: vuejs2 nuxt.js

我正在使用nuxt js。我在plugins文件夹中有一个helper.js脚本,它有一个简单的Test()方法。现在我如何从页面中使用这个Test()方法。

helper.js

document.addEventListener('keypress', (event) => {
  var newText = document.getElementById('the-text-area');
  sessionStorage.setItem('the_user_text', newText);
});

5 个答案:

答案 0 :(得分:2)

如果您只想使用组件(页面)中的代码,则只需导入并使用该方法:

<强> TestPage.vue

<template>
  <div>
    <h1>{{ getTest }}</h1>
  </div>
</template>

<script>
import test from '~/plugins/helper.js'

export default {
  computed: {
    getTest () {
      return test()
    }
  }
}
</script> 

答案 1 :(得分:2)

要访问整个应用程序的全局方法:


1-create ./plugins/helpers.js。


2-edit ./plugins/helpers.js:

import Vue from 'vue'
Vue.mixin({
    methods:{
        mySpecialMethod(value){
            console.log(value)
        },
    }
})

3-edit ./nuxt.config.js:

plugins: [
    ...
    { src: '~/plugins/helpers' },
    ...
],

现在您可以通过以下方式访问全局方法:

this.mySpecialMethod()

答案 2 :(得分:1)

您好,您可以通过以下操作将函数全局注入Vue:

./ plugins / myPluging.js

Import Vue from 'vue'

Vue.prototype.$nameOfMyPlugin = (args) => {
 // Code here
}

您可以通过以下方式访问所有组件:

./components/myComponent.vue

<script>
export default {
  name: 'c',
  mounted () {
   this.$nameOfMyPlugin('something useful')
 }
}

</script>

就是这样:)希望会有所帮助。

-参考:https://nuxtjs.org/guide/plugins/#inject-in-root-amp-context

答案 3 :(得分:1)

实际上有一种简单的方法可以通过使用“注入”方法来完成。 As described in the docs ...

在您的插件中只需使用如下注入:

export default ({ app }, inject) => {
  inject('myInjectedFunction', (string) => console.log('That was easy!', string))
}

,在您的组件中,您可以按以下方式使用它:

export default {
  mounted(){
    this.$myInjectedFunction('works in mounted')
  },
  asyncData(context){
    context.app.$myInjectedFunction('works with context')
  }
}

答案 4 :(得分:0)

以下是我在一个nuxt项目中使用过的自定义js插件。

  1. 在plugins文件夹中创建您的文件,并按以下方式创建自己的功能
export default (context, inject) => {
  const formatDate = (dateTime) => {
    if (typeof(dateTime) === 'undefined' || dateTime === null) {
      return null;
    }
    let tempDate = new Date(dateTime);
    tempDate.setMinutes(tempDate.getMinutes() -
      tempDate.getTimezoneOffset());
    tempDate = tempDate.toISOString().slice(0, 16);
    return tempDate;
  }
  // Inject $hello(msg) in Vue, context and store.
  inject('formatDate', formatDate)
  // For Nuxt <= 2.12, also add ?
  context.$formatDate = formatDate
}
  1. 将插件添加到nuxt.config.js,您将可以在全球范围内使用它。
相关问题