Vue.js 学习13 ElementUI项目中使用自定义组件
- 一、准备工作
- 二、实现过程
- 1. 新建自定义组件的文件夹及文件
- 2. 添加dialog代码
- 3. 调用方代码
一、准备工作
- 一个现成的ElementUI项目
本文目标:建立一个自定义的Dialog组件。
项目有person列表页面,要在列表页面点击按钮查看用户信息。
二、实现过程
1. 新建自定义组件的文件夹及文件
在src/views/person下
新建的index.vue代码大致如下:
<template>
</template>
<script>
export default {
data(){
return {
}
},
methods: {
}
}
</script>
<style scoped>
</style>
2. 添加dialog代码
<template>
<!-- 查看会员信息对话框 -->
<el-dialog :title="title" :visible.sync="dialogFormVisible" @close="closeDialog" width="1000px" append-to-body>
<el-row>
<el-col>昵称: {{form.nickName}}</el-col>
</el-row>
<div slot="footer" class="dialog-footer">
<el-button @click="closeDialog">关 闭</el-button>
</div>
</el-dialog>
</template>
<script>
import { getPerson } from "@/api/person";
export default {
// 传入参数
props:{
"dialogShow":{type:Boolean},
"title":{type:String},
"personId":{type:Number}
},
data(){
return {
dialogFormVisible: this.dialogShow,
form: { }
}
},
mounted() {
getPerson(this.personId).then(ret=>{
this.form = ret.data;
});
},
methods: {
closeDialog() {
// 向外部传递变量
this.$emit('dialogShowChange', false)
},
// 取消按钮
cancel() {
this.personDialogVisible = false;
}
}
}
</script>
<style scoped>
</style>
3. 调用方代码
<template>
<div class="app-container">
<el-table :data="personList" >
<el-table-column type="selection" width="55" align="center" />
<el-table-column label="编号" width="50" align="center" prop="id" />
<el-table-column label="用户名" align="center" prop="userName" />
<el-table-column label="操作" align="center" class-name="small-padding fixed-width">
<template slot-scope="scope">
<el-button
size="mini"
type="text"
@click="handleView(scope.row)"
>查看</el-button>
</template>
</el-table-column>
</el-table>
<div v-if="dialogShow" class="dialogBox">
<ViewPersonDialog :title="title" :dialogShow="dialogShow" :personId="personId" @dialogShowChange="dialogShowChange"></ViewPersonDialog>
</div>
</div>
</template>
<script>
import { listPerson } from '@/api/person'
import { viewPersonDialog } from '@/views/person/viewPersonDialog'
export default {
name: "Person",
components: {
//引入组件
viewPersonDialog
},
data() {
return {
// 会员信息表格数据
personList: [],
// 要查看的用户
personId:null,
// 弹出层标题
title: "查看用户",
// 是否显示弹出层
personDialogVisible: false,
dialogShow: false
};
},
created() {
// 加载列表
this.getPersonList();
},
methods: {
/** 查询会员信息列表 */
getPersonList() {
listPerson({}).then(response => {
this.personList = response.rows;
});
},
/** 查看按钮操作 */
handleView(row) {
this.reset();
this.personId = row.id || this.ids;
this.dialogShow=true;
},
// 组件传出的事件
dialogShowChange(val) {
console.log("val", val);
this.dialogShow = val
}
}
};
</script>