vue.js 2.0通信最佳实践

时间:2016-11-04 12:55:20

标签: javascript ecmascript-6 vue-component vue.js

我目前正在研究vue.js的一些内容,并想询问以下是否是一个好习惯。

我有一个父组件和子组件,例如dropdown和dropdown-item。当选择下拉项时,我通过this.$parent.dropdown.selected更改所选项目。这是一种很好的做法,还是应该通过活动来进行?

以下是代码:

<template lang="html">
  <div class="btn-group">
    <button class="btn btn-secondary dropdown-toggle"  @click="toggle" type="button">
      {{dropdown.selected.text}}
    </button>
    <div class="dropdown-menu" v-show="!isClosed">
      <slot></slot>
    </div>
  </div>
</template>

<script>
import DropdownItem from './dropdown-item.vue'

class Dropdown{
  constructor(name, selected, displayedItems) {
    this.name = name
    this.selected = new DropdownItem.uiClass("",selected)
    this.displayedItems = displayedItems
  }
}

export default {
  uiClass: Dropdown,
  name: "ui-dropdown",
  data() {
    return {
      isClosed: true
    }
  },
  props:{
    dropdown: Dropdown
  },
  methods: {
    toggle() {
      this.isClosed = !this.isClosed
    }
  }
}

<template lang="html">
  <a href="#" class="dropdown-item" @click.stop.prevent="select()"
    v-bind:class="{ 'active': value == $parent.dropdown.selected.value }">
    {{text}}
  </a>
</template>

<script>
class DropdownItem {
  constructor(value,text) {
    this.value = value
    this.text = text
  }
}

export default {
  uiClass: DropdownItem,
  name: "ui-dropdown-item",
  props:{
    value: String,
    text: String
  },
  computed: {
    dropdownItem() {
      return new DropdownItem(this.value, this.text)
    }
  },
  methods: {
    select() {
      this.$parent.dropdown.selected = this.dropdownItem;
      this.$parent.toggle()
    }
  }
}
</script>

感谢您的回复

1 个答案:

答案 0 :(得分:1)

没有。好的做法是从子节点发出事件并处理父节点中的数据。例如:

下拉项目组件:

<a 
  class="dropdown-item" 
  @click.stop.prevent="select()">
  {{text}}
</a>

methods: {
    select() {
      this.$emit('selected', this.item)
    }
}

父组件:

<div class="dropdown-menu" v-show="!isClosed">
  <dropdown-item @selected="selectItem"><dropdown>
</div>

methods: {
    selectItem(item) {
      this.selectedItem = item
    }
}

有关详情,请参阅Vue.js文档:https://vuejs.org/guide/components.html#Custom-Events