英文:
Reference reactive properties dynamically
问题
You can change reactive properties by referencing them dynamically in Vue 3 using the following code:
import { ref } from 'vue';
const page = ref('1');
const item = ref('1');
const product = ref('ok');
const note = ref(5);
const update = (object) => {
const properties = ['page', 'item', 'product', 'note'];
properties.forEach((prop) => {
if (prop in object) {
// Update the component property matching the current object key with the object property value
// For TypeScript, you can use Vue's `toRefs` to access the refs
// Make sure to define the type for `page`, `item`, `product`, and `note` beforehand
const targetRef = eval(prop); // Use eval to access the ref by its name
targetRef.value = object[prop];
}
});
};
const object = {
note: 'new value for note',
};
update(object);
This code dynamically updates the reactive properties based on the keys in the object. Make sure to define the types for page, item, product, and note if you are using TypeScript.
英文:
How can I change a reactive properties by referencing them dynamically?
If I have some reactive properties:
const page = ref('1');
const item = ref('1');
const product = ref('ok');
const note = ref(5);
Then there is a function that takes an object whis is supposed to update any of these properties. So I have an array with the names of the properties to match with the properties and the keys in the object.
const update = (object) = {
const properties = ['page', 'item', 'product', 'note'];
properties.forEach(prop => {
if(prop in object){
// update the component property matching the current object key by the object property value
// ? = object[prop]
}
}
}
const object = {
note: 'new value for note'
}
update(object);
Or is this not possible?
I would also need it to work with typescript.
答案1
得分: 1
你可以使用名为state的reactive函数来包装这些响应式属性:
const state = reactive({
page: '1',
item: '1',
product: 'ok',
note: 1,
})
const update = (object) => {
const properties = ['page', 'item', 'product', 'note']
properties.forEach((prop) => {
if (prop in object) {
state[prop] = object[prop]
}
})
}
const object = {
note: 'note的新值',
}
update(object)
英文:
You could wrap that reactive properties by reactive function named state :
const state = reactive({
page: '1',
item: '1',
product: 'ok',
note: 1,
})
const update = (object) => {
const properties: Array<keyof typeof state> = ['page', 'item', 'product', 'note']
properties.forEach((prop) => {
if (prop in object) {
state[prop] = object[prop]
}
})
}
const object: Partial<state> = {
note: 'new value for note',
}
update(object)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论