【问题标题】:Radiobutton-like behaving Vue.js components类似 Radiobutton 的 Vue.js 组件
【发布时间】:2016-03-13 13:30:28
【问题描述】:

我有以下 Vue.js 组件,它们基本上应该具有类似单选按钮的行为:

// Parent Component
<template>
  <child-component
    v-for="element in elements"
  </child-component>
</template>

<script>
import ChildComponent from './Child.vue'

export default {
  components: {
    ChildComponent
  },
  props: {
    elements: Array
  },
  methods: {
    activate(e) {
      for (let i of this.$children) {
        i.active = false;
      }

      if (e < this.$children.length) {
        this.$children[e].active = true;
      }
    }
  }
}
</script>

// Child Component
<template>
  {{active}}
</template>

<script>
export default {
  props: {
    active: Boolean
  }
}
</script>

这很好,但只有父母可以决定激活其中一个孩子(从而停用所有其他孩子)。

但我也希望能够允许每个孩子激活自己(并通过其父母的魔法属性,停用所有其他兄弟姐妹)。

显然我不希望每个孩子都知道他们的兄弟姐妹并弄乱他们的.active 道具(超级糟糕的设计)。

我宁愿不让孩子与父母沟通并调用一些方法(仍然是糟糕的设计,因为我只能在具有activate() 方法的父母中重用子组件。

相反,我希望父母听取所有孩子 active 道具的变化,并在其中一个发生变化时采取行动。这样,父级完全封装了单选按钮行为。

如何在 Vue.js 中实现这种交互?

【问题讨论】:

    标签: javascript components vue.js


    【解决方案1】:

    看看双向绑定:http://vuejs.org/guide/components.html#Prop_Binding_Types

    这允许您在两个方向同步属性的值,这意味着父级或子级有权更改变量。然后你可以观察父节点的变化并进行相应的更新。

    我认为更好的选择是创建一个 RadioSet 组件,该组件将容纳许多单选按钮。这将消除您对父母必须拥有activate() 方法的担忧。您可以简单地传入一个包含一系列idvalues 的对象,这些对象可用于生成按钮。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-08-19
      • 2019-05-03
      • 1970-01-01
      • 2021-08-23
      • 1970-01-01
      • 2010-10-26
      • 2022-11-16
      • 2018-09-27
      相关资源
      最近更新 更多