簡體   English   中英

對道具 Vue.js 的反應性

[英]Reactivity on props Vue.js

我剛開始學習 Vue,很難理解如何使用組合 API 定義道具等。

我有一個組件(ACE 編輯器),加載如下:

<v-ace-editor
    v-model:value="currentRecord.text"
/>

v-ace-editor需要像這樣加載模型和值: v-model:value

import {computed, ref} from 'vue';
import collect from "collect.js"

const props = defineProps({
    records: {
        type: Object,
    },
})

//Get all records.
let getRecords = () => {
    return collect(props.records)
}

//Filter the records using "collect.js"
const getUnlabeledRecords = () => {
    return getRecords()
        .where('skipped', false)
        .where('processed', false);
}

//Assign all unlabeled records on the first load.
let allRecords = ref(getUnlabeledRecords());

//In order to check if "text" is empty - and if not, set a default value, load the first record into a temp. variable.
let first = allRecords.value.first();
if(first){
    first.text ??= "";
}

//Load the current record into a ref.
let current = ref(first);

//Finally, compute it.
let currentRecord = computed(() => current.value)

看着這個,又是后台出身,感覺很臃腫。

我嘗試了以下方法:

let allRecords = ref(getUnlabeledRecords());
let currentRecord = computed(() => allRecords.value.first())

但是這樣做會導致我無法與currentRecord交互 - 也無法更改allRecords 這意味着,例如,如果后端的currentRecord.textnull ,我的 ace-editor 組件將失敗,因為它需要一個值。

還有其他方法可以加載這些變量嗎?

在模板中使用時,您實際上不必調用 ref 的 .value 。 因此,您實際上可以刪除計算部分(您的最后一行)並將您的模板更改為。

<v-ace-editor
    v-model="current.text"
/>

現在,假設您在 v-ace-editor 中正確管理了 v-model(如果這是您自己的組件),您應該在從 v-ace-editor 修改 current.text 時保持反應性。

附帶說明一下,計算屬性是只讀的。 您不能期望子組件通過使用 v-model 傳遞來修改其值。

但是,您應該注意,從父組件更新records prop 不會更新current 為此,也許您想在記錄上添加一個觀察者。

另外,個人建議,但是如果您只真正關心組件中的currentRecord而不是所有記錄,也許您應該從父組件進行過濾,並且僅將 currentRecord 作為道具傳遞。 其他個人建議,您可以在腳本中使用const而不是let聲明所有變量。 const防止重新分配,但是由於您使用 refs,因此您永遠不會重新分配它,而是更改其value屬性。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM