为什么 $emit 只在第一次点击时发送数据

时间:2021-05-30 17:45:52

标签: vue.js

我正在开发一个 VueJs 项目,我尝试将 数据 发送到另一个组件,但 $emit > 只在第一次点击时有效,我不知道为什么,这是我的代码:

有问题的函数是zz

<template>
  <li @click.stop="zz">
    <div :class="{ bold: isFolder }" @click="toggle">
      {{ model.name }}
      <span v-if="isFolder">[{{ open ? '-' : '+' }}]</span>
    </div>
    <ul v-show="open" v-if="isFolder">
      <item v-for="model in model.children" :key="model.name" class="item" :model="model"> </item>
      <li @click="addChild">+</li>
    </ul>
  </li>
</template>

<script>
export default {
  name: 'Item',
  props: {
    model: Object,
  },
  data() {
    return {
      open: false,
    }
  },
  computed: {
    isFolder() {
      return this.model.children && this.model.children.length
    },
  },
  methods: {
    toggle() {
      if (this.isFolder) {
        this.open = !this.open
      }
    },
    addChild() {
      this.model.children.push({
        name: 'new stuff',
      })
    },
    zz() {
      return this.$emit('do', this.model)
    },
  },
}
</script>

<style scoped>
.folder {
  cursor: pointer;
}
</style>

有人可以建议我解决我真的很累的解决方案吗,我现在想解决这个问题 3 天

1 个答案:

答案 0 :(得分:1)

找到解决办法:

因为我使用的是递归组件,所以我应该使用事件总线:

{
  "bar": "A"
}

家长:

<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" :key="model.nam"></item>
      <li class="add" @click="addChild">+</li>
    </ul>
  </li>
</template>

<script>
import Vue from 'vue'
var itemId = 0

export default {
    name: 'item',
    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.model);
      }
    },
    changeType: function() {
      if (!this.isFolder) {
        Vue.set(this.model, 'children', [])
        this.addChild()
        this.open = true
      }
    },
    addChild: function() {
      this.model.children.push({
        name: 'new stuff'
      })
    }
}
}
</script>

<style scoped>
.folder{
    cursor: pointer;
}
</style>

和电话:

import Vue from 'vue'
export default {
components: { item: item },
data() {
  return {
    treeData: {},
    bus: new Vue()
  };
},
created() {
  getAPI.get("api/folders/").then((response) => {
    this.treeData = response.data;
  });
  this.bus.$on('toggled', (who) => {
    console.log("Toggled", who);
  });
},
methods:{
  xyz(x){
    console.log("xyz: " +  x)
  }
}