从子组件中修改 props.value [英] Modify props.value from within child component

查看:28
本文介绍了从子组件中修改 props.value的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Vue 的新手,正在尝试构建一个下拉"组件.我想从这样的父组件中使用它:

I am new to Vue and trying to build a "dropdown" component. I want to use it from a parent component like this:

<my-dropdown v-model="selection"></my-dropdown>

其中 selection 作为 data 存储在父级上,并且应该更新以反映用户的选择.为此,我相信我的下拉组件需要一个 value 道具,并且需要在选择更改时发出 input 事件.

where selection is stored as data on the parent, and should be updated to reflect the user's selection. To do this I believe my dropdown component needs a value prop and it needs to emit input events when the selection changes.

但是,我也想从子本身内部修改 value,因为我希望能够自己使用下拉组件(我需要修改它,否则 UI 将如果组件单独使用,则不会更新以反映新选择的值).

However, I also want to modify the value from within the child itself, because I want to be able to use the dropdown component on its own (I need to modify it because otherwise the UI will not update to reflect the newly selected value if the component is used on its own).

有没有一种方法可以像上面那样绑定 v-model,而且还可以从子级内部修改值(似乎我不能,因为 value是一个道具,孩子不能修改自己的道具).

Is there a way I can bind with v-model as above, but also modify the value from within the child (it seems I can't, because value is a prop and the child can't modify its own props).

推荐答案

你需要有一个本地值的计算属性代理来处理输入/值.

You need to have a computed property proxy for a local value that handles the input/value values.

props: {
  value: {
    required: true,
  }
},
computed: {
  mySelection: {
    get() {
      return this.value;
    },
    set(v) {
      this.$emit('input', v)
    }
  }
}

现在您可以将模板设置为使用 mySelection 值来管理此组件内的数据,并且随着数据的变化,数据会正确发出并始终与 v-model 同步(selected) 当你在父级中使用它时.

Now you can set your template to use the mySelection value for managing your data inside this component and as it changes, the data is emitted correctly and is always in sync with the v-model (selected) when you use it in the parent.

这篇关于从子组件中修改 props.value的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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