安装 element-ui
npm install element-ui --save ---force
main.js 导入
import Vue from 'vue';
import ElementUI from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';
import App from './App.vue';
Vue.use(ElementUI);
new Vue({ el: '#app', render: h => h(App) });
创建弹框组件
在src/components
目录下创建一个ModalDialog.vue
文件。
<!-- eslint-disable vue/no-mutating-props -->
<template>
<el-dialog
:visible.sync="visible"
:title="title"
:width="width"
@close="handleClose"
>
<slot></slot>
<span slot="footer" class="dialog-footer">
<el-button @click="handleClose">取消</el-button>
<el-button type="primary" @click="handleConfirm">确定</el-button>
</span>
</el-dialog>
</template>
<script>
export default {
name: 'ModalDialog',
props: {
visible: {
type: Boolean,
default: false
},
title: {
type: String,
default: '弹框标题'
},
width: {
type: String,
default: '50%'
}
},
methods: {
handleClose () {
this.$emit('update:visible', false)
},
handleConfirm () {
this.$emit('confirm')
}
}
}
</script>
<style scoped>
/* 可根据需要自定义样式 */
</style>
在父组件中使用弹框组件
<template>
<div>
<h1>用户 ID: {{ userId }}</h1>
<h1>用户 userData: {{ userData }}</h1>
<p>这是用户详情页。</p>
<div>
<el-button type="primary" @click="showModal">打开弹框</el-button>
<ModalDialog
:visible.sync="isModalVisible"
title="自定义标题"
@confirm="handleConfirm"
>
<p>这是弹框的内容。</p>
</ModalDialog>
</div>
</div>
</template>
<script>
import ModalDialog from '../components/ModalDialog.vue'
export default {
name: 'App',
components: {
ModalDialog
},
data () {
return {
userId: null,
userData: null,
isModalVisible: false
}
},
created () {
this.userId = this.$route.params.id || this.$route.query.id
this.userData = this.$route.query.id
},
methods: {
showModal () {
this.isModalVisible = true
},
handleConfirm () {
this.isModalVisible = false
alert('确认按钮被点击')
}
},
beforeRouteUpdate (to, from, next) {
// 在路由发生变化,但组件实例被复用时调用
this.userId = to.params.id
next()
}
}
</script>