简体   繁体   English

如何从 Vue 应用程序中也使用“this”的外部文件导入方法

[英]How to import methods from external file that also use "this" in a Vue application

I have a vue file that has quite a few methods that I am looking to export into a separate file.我有一个 vue 文件,其中有很多方法,我希望将这些方法导出到一个单独的文件中。 The problem is some of these methods make use of the this keyword, and I can't figure out how to import these methods properly.问题是其中一些方法使用了this关键字,我不知道如何正确导入这些方法。 Here is a minimal example这是一个最小的例子

App.vue App.vue

export default {
  ...,
  data () {
    return { // assume these get generated properly through the app
        this.orderAmount = null,
        this.tax = null,
        this.totalAmount = null
        
    }
  },
  methods: {
    assignForAccount () {
      this.totalAmount = this.tax * this.totalAmount
      }
    }
}

I would like to move methods such as assignForAccount to a separate file called methods.js , but it I am getting undefined errors when I try to do this:我想将诸如assignForAccount之类的方法移动到一个名为methods.js的单独文件中,但是当我尝试这样做时出现undefined的错误:

App.vue App.vue

import { assignForAccount } from './methods.js'

export default {
  ...,
  data () {
    return { // assume these get generated properly through the app
        this.orderAmount = null,
        this.tax = null,
        this.totalAmount = null

    }
  },
  methods: {
       assignForAccount
    }
}

methods.js方法.js

export const assignForAccount = (context) => {
  context.totalAmount = context.tax * context.orderAmount
}

TIA TIA

You have to pass both this.tax and this.totalAmount from App.vue file into method.js file for the calculations.您必须将this.taxthis.totalAmount从 App.vue 文件传递到 method.js 文件中进行计算。

method.js :方法.js

export function assignForAccount = (tax, totalAmount) => {
    return tax * totalAmount
}

App.vue :应用程序.vue

import { assignForAccount } from './methods.js'

methods: {
    this.totalAmount = assignForAccount(this.tax, this.totalAmount);
}

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

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