最近用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"],