如何使 Vue 3 道具对象具有反应性?
How to make Vue 3 props objects reactive?
此代码来自VueMastery课程,必须过时:
export default {
setup(props, {emit}){
let email = props.email;
let toggleRead = () => {
email.read = !email.read
axios.put(`http://localhost:3000/emails/${email.id}`, email)
}
...
它给出了这个错误:
71:9 error Getting a value from the `props` in root scope of `setup()` will cause the value to lose reactivity vue/no-setup-props-destructure
请注意,我这里不是在处理 const。在 Vue 3 中使 prop 值具有反应性的正确方法是什么?
此警告是由旨在提高代码质量的 linter 规则引起的。如果已知某个 prop 在组件实例的生命周期内没有改变,则可以将其禁用。
这里的问题是代码改变了一个 prop,这被认为是一种不好的做法,可能会触发另一个警告。
对于 one-way prop 值的变化,即 parent 不知道它:
const toggleRead = () => {
const email = { ...props.email, read: !email.read };
axios.put(`http://localhost:3000/emails/${email.id}`, email)
}
对于 two-way 更改:
const toggleRead = () => {
...
emit('emailUpdate', email);
}
parent 应该监听 emailUpdate
事件并相应地更新其状态。
此代码来自VueMastery课程,必须过时:
export default {
setup(props, {emit}){
let email = props.email;
let toggleRead = () => {
email.read = !email.read
axios.put(`http://localhost:3000/emails/${email.id}`, email)
}
...
它给出了这个错误:
71:9 error Getting a value from the `props` in root scope of `setup()` will cause the value to lose reactivity vue/no-setup-props-destructure
请注意,我这里不是在处理 const。在 Vue 3 中使 prop 值具有反应性的正确方法是什么?
此警告是由旨在提高代码质量的 linter 规则引起的。如果已知某个 prop 在组件实例的生命周期内没有改变,则可以将其禁用。
这里的问题是代码改变了一个 prop,这被认为是一种不好的做法,可能会触发另一个警告。
对于 one-way prop 值的变化,即 parent 不知道它:
const toggleRead = () => {
const email = { ...props.email, read: !email.read };
axios.put(`http://localhost:3000/emails/${email.id}`, email)
}
对于 two-way 更改:
const toggleRead = () => {
...
emit('emailUpdate', email);
}
parent 应该监听 emailUpdate
事件并相应地更新其状态。