[英]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.tax
和this.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.