vue2.x中的父子组件

最近用element-ui开发一个项目的前端,用的vue2.4.2,用到了不同组件的交互。

一、新建两个vue文件:

1、父组件:index.vue

<template>
  <div class="app-container">
	<!-- 按钮:弹出子组件对话框 -->
	<el-button type="primary" icon="edit" size="small" class="editBth" @click="handRulesList">
	   规则管理
	 </el-button>
  
    <!-- 弹出对话框 -->
    <el-dialog title="子组件" :visible.sync="rulesManageVisible" size="full" :modal="false">
    	<!-- 显示子组件 -->	
        <sysRulesManage ref="RulesManage" @loadingIndex="loading" :test="text"></sysRulesManage>
    </el-dialog>

  </div>
</template>
<script>
  //导入组件
  import sysRulesManage from '@/views/sysRulesManage.vue';

 export default {
   //注册组件
   components:{
      sysRulesManage
    },
    data() {
      return {
        //隐藏/显示子组件
        rulesManageVisible: false,
        
        text: '测试文字',
      }
    },
    created() {
	
    },
    methods: {
      loading: function(){
		alert("加载方法");
	  },
      //点击‘规则管理’按钮
      handRulesList:function(){
          this.rulesManageVisible = true;
          
          setTimeout(()=>{
              //与子组件通信
          	  this.$refs.RulesManage.modelObjId = "1111";
              this.$refs.RulesManage.init();
          },60);
      },
    }
  };
</script>

<style scoped>
  
</style>

2、子组件:sysRulesManage.vue

<template>
    <div class="app-container">
    </div>
</template>

<script>
    export default {
        props: ["test"],
        //注册组件
        components:{
            
        },
        data() {
            return {
                //模型对象id
                modelObjId: null,
            }
        },
        created() {
            
        },
        methods: {
            init: function(){
                debugger
                alert(this.modelObjId);

                //与父组件通信
                alert(this.test);
                this.$emit("loadingIndex");
            },
        }
    };
</script>

<style scoped>

</style>

二、实现步骤:

1、导入子组件:
 

import sysRulesManage from '@/views/sysRulesManage.vue';

2、在components事件中注册组件:

components:{
      sysRulesManage
  },

也可以这样写:

components:{
      'sysRulesManage': sysRulesManage
 },

3、在页面使用子组件:

ref属性:被用来给元素或子组件注册引用信息,引用信息将会注册在父组件的 $refs 对象上。

@loadingIndex:注入一个方法。子组件与父组件通信时使用this.$emit调用。

:test:注入一个方法。将父组件的属性text注入子组件,并且命名为test。

<sysRulesManage ref="RulesManage" @loadingIndex="loading" :test="text"></sysRulesManage>

4、父组件与子组件通信:this.$refs

this.$refs.RulesManage.modelObjId = "1111";
this.$refs.RulesManage.init();

注:在使用子组件的属性\方法是时候需要延迟一点,让子组件加载完,不然会报异常:

setTimeout(()=>{
     this.$refs.RulesManage.modelObjId = "1111";
     this.$refs.RulesManage.init();
 },60);

5、子组件与父组件通信:

5.1、子组件使用父组件的方法:this.$emit

this.$emit("loadingIndex");

5.2、子组件使用父组件的属性:

使用props事件接收,就能直接使用了:this.test;

props: ["test"],

6、运行效果:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值