这是您尝试做的一个可能的实现
<TextField v-model="newItem.unitPriceExcl" @textChange="calcPricing" keyboardType="number" @focus="focus" @blur="blur" hint="Unit Price Excl"></TextField>
<TextField v-model="newItem.unitPriceIncl" @textChange="calcPricing" keyboardType="number" @focus="focus" @blur="blur" hint="Unit Price Incl"></TextField>
...
data: () => ({ focusedElement: null })
methods: {
focus({ object }) {
this.focusedElement = object;
},
// You don't have to handle blur depending on your logic, but I find it more consistent
blur({ object }) {
if (this.focusedElement !== object) return;
this.focusedElement = null;
}
}
...
如果您不是真的想知道哪个元素具有焦点,而是想知道修改来自哪个元素。你可以这样做:
<TextField v-model="newItem.unitPriceExcl" @textChange="calcPricing('unitPriceExl')" keyboardType="number" hint="Unit Price Excl"></TextField>
...
methods: {
calcPricing(name) {
return (args) => {
// Your logic goes here, you have access to name, and to args
}
}
}
...
旁注:您还可以使用一些本机方法来查找当前焦点所在的视图。不过要注意,它不是更快,也不推荐,主要思想是使用NS common api。
<TextField v-model="newItem.unitPriceExcl" @textChange="calcPricing" keyboardType="number" hint="Unit Price Excl" ref="unitPriceExcl"></TextField>
...
let UIResponder;
if (isIOS) {
UIResponder = (UIResponder as any).extend({
currentFirstResponder() {
this.currentFirstResponder = null;
UIApplication.sharedApplication.sendActionToFromForEvent('findFirstResponder', null, null, null);
return this.currentFirstResponder;
},
findFirstResponder(application: UIApplication) {
this.currentFirstResponder = new WeakRef(self)
}
}, {
exposedMethods: {
currentFirstResponder: { returns: UIView, params: [ ] }
}
})
}
...
methods: {
getFocusedView() {
if (isAndroid) {
const activity = application.android.foregroundActivity;
if (activity) {
return activity.getCurrentFocus()
}
} else if (isIOS) {
return UIResponder.currentFirstResponder;
}
return null;
},
isFocused(object) {
if (object.nativeView && object.nativeView.nativeView) return false;
return this.getFocusedView() === object.nativeView.nativeView;
},
calcPricing(args) {
if (this.isFocused(this.$refs.unitPriceExcl)) {
console.log('unitPriceExcl is selected');
}
},
}
...