Technologies:
Tolerim
an hour ago
How does the object get returned by a computed function in Vue3?
I notice that some individuals are experimenting with code in a manner that could be detrimental to Vue's single data flow. I believe that it's not advisable to use computed in such a way either. Here's the code for the child component:
<template>
<el-switch
v-model="customConfig.switchValue"
active-color="#13ce66"
@change="customConfig.change"
inactive-color="#ff4949">
</el-switch>
</template>
...
props: {
customConfig: {
type: Object,
default: () => ({})
}
},
setup(props, { emit }) {
const customConfig= computed(() => {
return Object.assign({}, props.customConfig) //is right?
})
const change = (e) => {
console.log( e)
}
return {
customConfig,
}
}
The following code represents the parent component:
<custom-switch
:customConfig="customConfig"
/>
const customTabsConfig = reactive({
switchValue:false,
change: (index: number) => {
console.log(index)
},
})
Is it not true that computed's value is altered by other values? If you use computed in this way, could it not potentially disrupt the data flow between parent and child components?Answers(1)
Tolerim
an hour ago
Verified Answer
This code is using Vue 3 Composition API's setup() function, which is a way to create components using functions instead of options objects. In this case, the child component is accepting a prop customConfig and creating a computed value based on it, which is then used to control the state of an element.
Regarding the question of whether this breaks Vue's single data stream, it does not. The computed property being used in the child component is based on the prop passed down from the parent component, so any changes made to it will affect the state of the element in the child component. The Object.assign() method is being used to create a new object based on the props.customConfig object, so any changes made to the computed property will not affect the original object in the parent component.
Using computed properties in this way can be a useful way to create derived data based on passed props, but it's important to make sure that any changes made to the computed property do not affect the original prop or other components.