Vue.js改变道具 [英] Vue.js Changing props

查看:170
本文介绍了Vue.js改变道具的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对如何更改组件内的属性感到有点困惑,假设我有以下组件:

I'm a bit confused about how to change properties inside components, let's say I have the following component:

{
    props: {
        visible: {
            type: Boolean,
            default: true
        }
    },
    methods: {
         hide() {
              this.visible = false;
         }
    }
} 

虽然它有效,但它会发出以下警告:

Although it works, it would give the following warning:


避免直接改变道具,因为只要父组件重新渲染,该值就会被覆盖。而是根据prop的值使用数据或计算属性。支持变异:可见
(在组件中找到)

Avoid mutating a prop directly since the value will be overwritten whenever the parent component re-renders. Instead, use a data or computed property based on the prop's value. Prop being mutated: "visible" (found in component )

现在我想知道最好的处理方法是什么这显然是在DOM中创建组件时传入 visible 属性:< Foo:visible =false>< / Foo>

Now I'm wondering what the best way to handle this is, obviously the visible property is passed in when created the component in the DOM: <Foo :visible="false"></Foo>

推荐答案

引用你的小提琴

不知何故,你应该决定一个的地方生活的国家,而不是两个。我不知道是否更适合将它放在 Alert 中,或者只是在它的用例中使用它,但是你应该选择一个。

Somehow, you should decide on one place for the state to live, not two. I don't know whether it's more appropriate to have it just in the Alert or just in it's parent for your use case, but you should pick one.

父母或兄弟姐妹成员是否依赖于州?

Does the parent or any sibling component depend on the state?


  • 是:那么它应该在父母(或在某些外部州管理中)

  • 否:那么它更容易拥有它处于组件本身的状态

  • 有点:见下文

在一些罕见的情况下例如,您可能想要一个组合。也许你想让父母和孩子都有隐藏孩子的能力。然后你应该在父母和孩子都有状态(所以你不必在孩子里面编辑孩子的道具)。

In some rare cases, you may want a combination. Perhaps you want to give both parent and child the ability to hide the child. Then you should have state in both parent and child (so you don't have to edit the child's props inside child).

例如,如果出现以下情况,孩子可以看到: 可见&& state_visible ,其中 visible 来自props并反映父级状态的值, state_visible 来自孩子的状态。

For example, child can be visible if: visible && state_visible, where visible comes from props and reflects a value in the parent's state, and state_visible is from the child's state.

我不确定这是否是你想要的行为,但这里是一个小提琴。我会假设您实际上只想在单击子组件时调用父组件的 toggleAlert

I'm not sure if this is the behavour that you want, but here is a fiddle. I would kinda assume you actually want to just call the toggleAlert of the parent component when you click on the child.

这篇关于Vue.js改变道具的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆