Vue父组件传对象给子组件

Home / Article MrLee 2020-7-21 3684

在子组件中调用父组件的方法,默认this.$parent可以正常使用,但是这种方法存在很大的问题。比如嵌套,那基本上就废了。思来想去,只能通过传父组件this比较靠谱,不会跑飞到宇宙中去~~~

重点

在子组件中通过props来接受父组件传的数据 

          props: { //可以指定属性具体的数据类型哦!

            'title': String,

            'people': Number,

            'add': Function,

            'parent': Object

          }

子组件:@node-click="this.parent.handleNodeClick"

<template>
<div>
            <el-tree :data="$store.state.cache.types"
                   :default-expanded-keys="[2, 96]"
                   node-key="id"
                   @node-click="this.parent.handleNodeClick">
            <span slot-scope="{ node, data }">
              <span v-if="data.children && data.children.length>0">
                <i class="iconfont iconwenjianjia-"></i>
              </span>
              <span v-else>
                <i class="iconfont iconjishibu-"></i>
              </span>
              <span style="padding-left:4px; font-weight: bold">
                {{ data.name }}
              </span>
            </span>
          </el-tree>
</div>
export default {
  name: 'incSearch',
  data () {
  },
  props: {
    'parent': Object
  },
  methods: 
  }
}

子组件中的template代码注册事件返回父组件处理

父组件(代码片段):

<template>
<div>
    <incsearch :parent="this"></incsearch>
</div>
</template>
<script>
import incsearch from './incSearch'
......
components: {
    incsearch
  },
......
</script>


PS:父组件调用子组件方法

使用ref即可实现,不过要注意dialog机制,在dialog中使用ref可能是第一时间获取不到对象的,因为dialog还未正常渲染出来,所以要监听dialog是否加载完成,这里最简单处理方法延迟调用就OK了。

      setTimeout(() => {
        if (_this.$refs.searchDialog !== undefined &&
          typeof (_this.$refs.searchDialog.test) === 'function') {
          ......
        }
      }, 10)


本文链接:https://www.it72.com/12652.htm

推荐阅读
最新回复 (0)
返回