我有一個簡單的 Vue 組件,它來自 3rd 方包。
該組件是一個文本編輯器,我必須為其提供一個值才能正確呈現。
<SomeComponent v-model:value="text" />
<script setup>
const props = {
records: {
type: Object,
},
}
const text = computed(() => props.records.first())
</script>
現在,我想在每次text更改屬性時更新我的??資料庫。
watch(text, () => {
//Post to database...
})
但是,我不想在每次擊鍵時都更新資料庫——因此,我想讓懶惰的人變得v-model懶惰。我正在嘗試這樣做:
<SomeComponent v-model:value.lazy="text" />
但是,這不起作用。我的watch方法中的代碼在每次擊鍵時都會被觸發。
uj5u.com熱心網友回復:
如檔案所示,v-model只是一些糖語法。
所以那些是一樣的
<input v-model="text">
<input :value="text" @input="event => text = event.target.value">
如果您想在更改事件上更新您的組件,那么您可以使用類似這樣的東西
<SomeComponent :value="text" @change="event => text = event.target.value" />
或者這個比較
<SomeComponent v-model.lazy="text" /> <!-- text is the getter and the setter here -->
如檔案所示:https ://vuejs.org/guide/essentials/forms.html#lazy
如果你想要更高級的東西,你可以考慮去抖動你的輸入(更多的作業,但處理何時更新狀態更聰明)。
uj5u.com熱心網友回復:
你不需要使用
v-model:value="text",就v-model="text"足夠了。如果您希望輸入是惰性的,沒有任何額外的功能(例如每次更改都發布到資料庫),那么
v-model.lazy="text"就足夠了。使用 時
watch,您的輸入是延遲更新還是立即更新都沒有關系。觀察者監視每一個變化,即:在輸入的情況下的每一次擊鍵。
因此,如果您希望讓它變得懶惰并在每次更改時呼叫 DB,那么您需要這樣做:
<SomeComponent :value="text" @change="onChange">\
<script setup>
const onChange = (event) => {
text.value = event.target.value;
// post to DB
}
</script>
如果這不起作用,那么嫌疑人是第 3 方包。在這種情況下,我建議您查看包的檔案,看看它們是否為文本編輯器提供了一個懶惰的道具。
uj5u.com熱心網友回復:
第 3 方插件不允許我省略該v-model:value屬性,所以我最終改用 lodash 的 debounce方法:
<SomeComponent v-model:value.lazy="text" />
watch(text, _.debounce(function () {
//Post to database...
}, 500));
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/473266.html
上一篇:新網址未在新標簽頁中打開
