vue2 封装弹框组件

安装 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>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值