簡體   English   中英

如何從 Vue 應用程序中也使用“this”的外部文件導入方法

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

我有一個 vue 文件,其中有很多方法,我希望將這些方法導出到一個單獨的文件中。 問題是其中一些方法使用了this關鍵字,我不知道如何正確導入這些方法。 這是一個最小的例子

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

我想將諸如assignForAccount之類的方法移動到一個名為methods.js的單獨文件中,但是當我嘗試這樣做時出現undefined的錯誤:

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

方法.js

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

TIA

您必須將this.taxthis.totalAmount從 App.vue 文件傳遞到 method.js 文件中進行計算。

方法.js

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

應用程序.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