Vue 3 不支持更改对象/数组的内部属性值吗? #8499
Answered
by
chenxch
yetrun
asked this question in
Help/Questions
-
Vue 3 指南中单向数据流一节有这么一段话:
但在实际开发中,直接修改对象的内部值,是很方便的实现方式。比如,对于绑定一个表单应用: <!-- UserForm.vue -->
<template>
<form @submit="submit">
<input type="text" v-model="user.name">
<input type="number" v-model="user.age">
<button type="submit">Submit</button>
</form>
</template>
<script setup lang="ts">
const props = defineProps<{
syncUser: { name: string, age: integer } // 取这么个属性名是为了向调用者告知一下内部的属性值会被子组件改掉
}>()
const emit = defineEmits{
(e: 'submit': user: { name: string, age: integer })
}()
const user = computed(() => props.syncUser)
function submit() {
emit('submit', props.user)
}
</script> 调用者如果没有什么特殊的要求,则直接使用即可: <template>
<UserForm :sync-user="user" @submit="submit"></UserForm>
</template>
<script setup lang="ts">
const user = ref({ name: '', age: 0 })
const submit = async function(user) {
await remoteSave({ user: user })
}
</script> 我有两个疑问:
希望懂行的人士能够答疑解惑。 |
Beta Was this translation helpful? Give feedback.
Answered by
chenxch
Jun 5, 2023
Replies: 2 comments
-
#8256 这里有讨论过哦 |
Beta Was this translation helpful? Give feedback.
0 replies
Answer selected by
yetrun
-
关于性能损耗的说法,我是否可以这么理解?如果父组件只用到对象引用,没用到对象的内部元素,是否子组件在内部修改时就不会造成父组件重新渲染?像这样:
父组件只用到:
<template>
<UserForm :sync-user="user" @submit="saveUser" />
</template>
<script setup>
const user = ref({})
const saveUser = () => {
remoteSaveUser(user.value)
}
</script>
原始邮件
发件人:"weajer"< ***@***.*** >;
发件时间:2023/6/6 10:39
收件人:"vuejs/core"< ***@***.*** >;
抄送人:"Yet Run"< ***@***.*** >;"Mention"< ***@***.*** >;
主题:Re: [vuejs/core] Vue 3 不支持更改对象/数组的内部属性值吗? (Discussion #8499)
Vue 3 指南中提到了单向数据流的概念,主要是为了遵循数据的可追踪性和更好的组件通信。在父组件向子组件传递 props 时,子组件应该被设计为无法直接修改这些 props 的绑定值,主要有几个好处:
数据追踪:Vue 可以更好地追踪数据的变化和依赖关系,从而提高性能和响应能力。
组件通信:通过强制使用 props 的单向数据流,可以更清晰地定义组件之间的通信方式,使代码更易于理解和维护。
避免意外的副作用:直接修改父组件传递的 props 可能会导致意外的副作用,因为其他地方可能仍然依赖于原始的 props 值。
针对 @yetrun 的两个疑惑,解答如下:
A1:为什么不推荐?
Q1:参考上面的回答,其实这就是一种最佳实践。因为我们开发代码的大部分时间其实在维护,所以更清晰的逻辑是非常重要的。
A2:性能损耗
Q2:假设在子组件可以更新 props,由于 props 是父组件的状态,当更新 props 时也会更新父组件中的状态,从而导致父子组件都频繁的重新渲染;而正常来说,在编辑 user 信息时,我只需要子组件进行更新,而父组件只在 emit submit 事件时才更新。对比而来,直接修改 props 则会带来一定的性能损失。
—
Reply to this email directly, view it on GitHub, or unsubscribe.
You are receiving this because you were mentioned.Message ID: ***@***.***>
|
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
#8256 这里有讨论过哦