【问题标题】:Hierarchical Component not sending emit in Vue js分层组件不在 Vue js 中发送发射
【发布时间】:2022-11-22 15:04:29
【问题描述】:

您好我正在尝试实现树视图。我有一个分层的组件。我面临的问题是 emit 在树组件内部不起作用。请帮帮我。这是我的代码...

TreeItem.vue

<template>
  <div class="node" :style="{ marginLeft: depth * 20 + 'px' }">
    <span class="menu-item" v-if="type == 'country'">
            <button class="menu-button menu-button--orange" @click="addState()">
              Add State
            </button>
          </span>
<TreeItem
      v-if="expanded"
      v-for="child in node.children"
      :key="child.name"
      :node="child"
      :depth="depth + 1"
    />
</div></template>

<script>
export default {
  name: "TreeItem",
  props: {
    node: Object,
    depth: {
      type: Number,
      default: 0,
    },
    emits: ["add-state"],
  },
  data() {
    return {
      expanded: false,
    };
  },
methods: {
 addState() {
      console.log("Adding State"); //Prints this message to console
      this.$emit("add-state");
    },

},
};

</script>

地址管理器.vue
内部模板:

 <div>
          <tree-item :node="treedata" @add-state="addState"></tree-item>
        </div>

内部方法:

addState() {
      console.log("State will be added"); //Never prints this message
    },

我们需要在按钮点击时发出。但是发射不起作用。

【问题讨论】:

    标签: javascript html vue.js components


    【解决方案1】:

    所以我已经弄清楚了问题......我们需要用this.$parent.$emit()替换this.$emit()

    这是变化-

    addState() {
          console.log("Adding State"); //Prints this message to console
          this.$parent.$emit("add-state");
        },
    

    希望这解决了我的问题。

    【讨论】:

      【解决方案2】:

      您可以使用 v-on="$listeners" 在深度 https://v2.vuejs.org/v2/guide/components-custom-events.html#Binding-Native-Events-to-Components 内传递高于级别的发射,它只会将它们转发给父级。

      然而,在嵌套场景中,使用 store (vuex) 并分配一个属性然后从任何你想注意到其变化的地方观察属性变化会更方便。如果你使用 vuex: https://vuex.vuejs.org/api/#watch store properties 可以查看。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-02-12
        • 2022-01-15
        • 2022-01-05
        • 1970-01-01
        • 2020-01-22
        • 2018-03-07
        • 2020-10-16
        相关资源
        最近更新 更多