【问题标题】:VueJs Tree recursive elements emits to parentVueJs 树递归元素向父级发出
【发布时间】:2018-02-23 12:04:54
【问题描述】:

如何在递归子组件 vuejs 中发出事件

以 vue 站点 https://vuejs.org/v2/examples/tree-view.html 中的树为例

您将如何在点击时将每个点击的元素 id 传递给父级?

【问题讨论】:

  • 你有什么尝试吗?
  • 是的,我试图用 vuex 管理状态,与 redux 有很多相似之处,但没有明白这一点

标签: vue.js parent children emit


【解决方案1】:

如果您不想创建多个 Vue 实例,这是另一种解决方案。我在我的单文件递归组件中使用它。

它使用v-on 指令(我使用的是@ 简写)。

在你的递归组件<template>:

<YourComponent @bus="bus"></YourComponent>

在递归组件中methods

methods: {
    bus: function (data) {
        this.$emit('bus', data)
    }
}

要启动它,您需要在子级中发出一个事件:

this.$emit('bus', {data1: 'somedata', data2: 'somedata'})

该数据将一直沿链向上传输,然后您在调用递归组件的页面中收到该事件:

methods: {
    bus (data) {
        // do something with the data
    }
}

这是一个在 Vue.JS 树示例中展示它的小提琴。右键单击一个元素,它将在控制台中输出该模型:

https://jsfiddle.net/AlanGrainger/r6kxxoa0/

【讨论】:

  • 难道不是每个孩子/父母都会收到这个事件吗?如果您有一棵树中的树中的树(3 深),来自孙子的“总线”事件将在父母和祖父母中触发,是吗?
  • @LucasMorgan 无论你把树做得多深,它都会向上穿过树一直到顶部。检查小提琴,你可以看到它在行动。
  • 什么是“contextmenu”事件?我搜索它但一无所获。 :)
  • 你是男人
【解决方案2】:

对于递归元素,您可以在父级中创建一个event bus,将其作为道具传递给子级,然后让每个道具将其传递给它们生成的任何子级。

每个子节点在总线上发出事件,父节点处理它们。我复制了您链接的树视图练习并添加了总线功能。

// demo data
var data = {
  name: 'My Tree',
  children: [{
      name: 'hello'
    },
    {
      name: 'wat'
    },
    {
      name: 'child folder',
      children: [{
          name: 'child folder',
          children: [{
              name: 'hello'
            },
            {
              name: 'wat'
            }
          ]
        },
        {
          name: 'hello'
        },
        {
          name: 'wat'
        },
        {
          name: 'child folder',
          children: [{
              name: 'hello'
            },
            {
              name: 'wat'
            }
          ]
        }
      ]
    }
  ]
};

var itemId = 0;

// define the item component
Vue.component('item', {
  template: '#item-template',
  props: {
    model: Object,
    bus: Object
  },
  data: function() {
    return {
      open: false,
      id: ++itemId
    }
  },
  computed: {
    isFolder: function() {
      return this.model.children &&
        this.model.children.length
    }
  },
  methods: {
    toggle: function() {
      if (this.isFolder) {
        this.open = !this.open;
        this.bus.$emit('toggled', this.id);
      }
    },
    changeType: function() {
      if (!this.isFolder) {
        Vue.set(this.model, 'children', [])
        this.addChild()
        this.open = true
      }
    },
    addChild: function() {
      this.model.children.push({
        name: 'new stuff'
      })
    }
  }
})

// boot up the demo
var demo = new Vue({
  el: '#demo',
  data: {
    treeData: data,
    bus: new Vue()
  },
  created() {
    this.bus.$on('toggled', (who) => {
      console.log("Toggled", who);
    });
  }
})
body {
  font-family: Menlo, Consolas, monospace;
  color: #444;
}

.item {
  cursor: pointer;
}

.bold {
  font-weight: bold;
}

ul {
  padding-left: 1em;
  line-height: 1.5em;
  list-style-type: dot;
}
<script src="//cdnjs.cloudflare.com/ajax/libs/vue/2.4.2/vue.min.js"></script>
<!-- item template -->
<script type="text/x-template" id="item-template">
  <li>
    <div :class="{bold: isFolder}" @click="toggle" @dblclick="changeType">
      {{model.name}}
      <span v-if="isFolder">[{{open ? '-' : '+'}}]</span>
    </div>
    <ul v-show="open" v-if="isFolder">
      <item class="item" :bus="bus" v-for="model in model.children" :model="model">
      </item>
      <li class="add" @click="addChild">+</li>
    </ul>
  </li>
</script>

<p>(You can double click on an item to turn it into a folder.)</p>

<!-- the demo root element -->
<ul id="demo">
  <item class="item" :bus="bus" :model="treeData">
  </item>
</ul>

【讨论】:

  • 非常感谢 sn-p 正在工作。使用 vuex 管理这种状态的最佳方法是什么?
【解决方案3】:

Use v-on="$listeners"

我会让你知道一个小秘密。 Vue $listeners 属性(被记录为将事件传递给孩子)也将孩子事件传递给父母!

https://vuejs.org/v2/guide/components-custom-events.html#Binding-Native-Events-to-Components

这是一个伪代码示例(用于说明目的的简写):

<ancestor-component @messageForAncestor="displayMessage">
  ...
  <parent-component v-on="$listeners">
    ...
    <child-component @click="$emit('messageForAncestor')">

在子组件上方的显示中会传递一个事件。父级通常能够侦听messageForAncestor 事件,这就是它需要停止的地方,但是。将v-on="$listeners" 放在父母身上实际上是说请传递它

警告:这可能是个坏主意

不过,这可能是一个非常糟糕的主意。一个更好的主意是简单地要求中间组件(父级)传递它......

<!-- better idea (listen for message and pass on message) --> 
<parent-component @message="$emit('message', $event)">

【讨论】:

  • 您能解释一下为什么这是个坏主意吗?
  • @sousdev Vue 中事件的传播得到了很好的控制。事件上升,属性下降。而且它们只会上升 1 级。组件标签必须在其中“监听事件”,然后再次重新发出它们以将其传递到链上。当您使用 v-on="$listeners" 时,它会向上和向下传递所有事件。这意味着子组件中的任何事件都将自动向上传递给祖先,并且事件也会向下传递。这意味着意外的侦听器可能会收到事件。绝对不要使用像“click”这样的事件名称,因为可能有现有的侦听器正在监听它们。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-02-15
  • 1970-01-01
  • 2017-11-06
  • 2021-08-24
  • 2019-08-22
  • 2016-10-24
  • 1970-01-01
相关资源
最近更新 更多