我有一個使用 Quasar 的 vue 應用程式,該應用程式在選擇影像后加載模式以執行功能。這適用于固定值,但我無法讓它適用于動態創建的欄位(這意味著用戶可以通過單擊“添加欄位”按鈕來添加它們)。
問題我想創建一個在三個欄位(imgOne、imgTwo 和 imgThree)中的每一個上觸發的觀察者。我可以使用 deep 修飾符在更改陣列時觸發它,但這不適用于我的目的。
額外問題:如何允許在不觸發監視的情況下清除檔案輸入欄位。
<q-file
v-model="map"
label="map"
></q-file>
<div
v-for="(field, i) in fields"
:key="i"
>
<q-file
v-model="fields[i].imgOne"
></q-file>
<q-file
v-model="fields[i].imgTwo"
></q-file>
<q-file
v-model="fields[i].imgThree"
></q-file>
</div>
watch(map, (currentValue, oldValue) => {
//this works to launch the modal
});
watch(
fields.imgOne,
(currentValue, oldValue) => {
//this does not work. I cannot use fields[i].imgOne or
//fields.value.imgOne
//I want this to fire each time imgOne, imgTwo, or
//imgThree change
},
{ deep: true }
);
uj5u.com熱心網友回復:
為陣列中的每個條目維護單獨的觀察者fields(如果您想要單獨的觀察者,則為 3 個觀察者imgOne等imgTwo- 從問題中不清楚)絕對是可能的,但您需要解決一些問題:
- 每次添加新欄位時都必須添加觀察者
- 當欄位被洗掉時,您可能應該存盤回傳值
watch以停止觀察者 - 由于
fields陣列的元素是反應物件而不是s,所以必須使用接收函式ref的多載watch
// after new field with index addedFieldIndex is added into array
// local variable
const addedFieldIndex = XX
const field = fields[addedFieldIndex]
field.watcher = watch(
// watching multiple sources at once
[
() => field.imgOne,
() => field.imgTwo,
() => field.imgThree
], handler)
無論如何,這絕對是不必要和復雜的。watch在這種情況下,恕我直言,這不是最好的工具。更好的工具是在選擇或清除檔案時觸發的update:model-value事件(由 使用的相同事件)v-model
<q-file
v-model="fields[i].imgThree"
@update:model-value="onFileSelected(field, $event)"
></q-file>
const onFileSelected = (field, fileSelected) => {
// null is used when field is cleared
if(fileSelected !== null) {
console.log("File ", fileSelected, " for field ", field.id)
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/418949.html
標籤:
