javascript - vue.js 2.0 通信最佳实践

标签 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>

感谢您的回复

最佳答案

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

下拉项组件:

<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

关于javascript - vue.js 2.0 通信最佳实践,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40423231/

相关文章:

ecmascript-6 - 嵌套对象的解构和重命名

html - 为什么不工作

javascript - vue js vue-slider-component 如何更新 Prop

javascript - TradingView 未在 Vue 挂载钩子(Hook)中定义

javascript - Rails 编译的 javascript 资源调试

javascript - 包含的 Javascript 页面的路径

javascript - 如何使用普通 JavaScript (ES6) 处理 ajax 请求?

javascript - 在 Unity 上运行 Javascript 代码出现错误。

javascript - 使用push和shift方法反转数组

javascript - Div 内带有 Link 的 VueJS Button 也会触发 href 链接