[英]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.text
为null
,我的 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.