vue.js - vue 递归组件自定义事件问题

查看:1107
本文介绍了vue.js - vue 递归组件自定义事件问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

递归组件,事件只执行一次

子组件

<template>
  <ul class="tree">
    <li>
      <span v-html="data.title" @click="nodeClick(data.title)"></span>
      <m-tree v-for="(item , idx) in data.children" :data="item" :key="idx"></m-tree>
    </li>
  </ul>
</template>

<script>
  export default {
    name: 'mTree',
    props: {
      data: {
        type: Object,
        default (){
          return {}
        }
      }
    },
    methods: {
      nodeClick(title){
        this.$emit('nodeClick',title);
      }
    }
  }
</script>

父组件

<template>
  <div id="app">
    <Tree :data="data" @nodeClick="nCllick"></Tree>
  </div>
</template>

<script>
  import Tree from './components/tree.vue'
  export default {
    components: {Tree},
    name: 'app',
    data(){
      return {
        data: {
          'title': '111',
          'children': [
            {
              'title': '111 - 1'
            }, {
              'title': '111 - 2',
              'children': [
                {'title': '111 - 2 - 1'}
              ]
            }
          ]
        }
      }
    },
    methods: {
      nCllick(title){
          console.log(title)
      }
    }

  }
</script>

运行截图

我想点击每一行,都打印出当前的内容,可是只执行一次;
看其他ui库的源码,是用了循环到根实例,parent.$emit.call(parent,par);不知道具体解决方法,请大神赐教!

解决方案

在组件中调用一下事件

<template>
  <ul class="tree">
    <li>
      <span v-html="data.title" @click="nodeClick(data.title)"></span>
      <m-tree v-for="(item , idx) in data.children" :data="item" :key="idx" @nodeClick="outClick"></m-tree>
    </li>
  </ul>
</template>

<script>
  export default {
    name: 'mTree',
    props: {
      data: {
        type: Object,
        default (){
          return {}
        }
      }
    },
    methods: {
      nodeClick(title){
        this.$emit('nodeClick',title);
      },
      outClick(title){
          this.$emit('nodeClick',title);
      }
    }
  }
</script>

这篇关于vue.js - vue 递归组件自定义事件问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆