UniApp UView 框架下自定义 Modal 组件封装教程

本文将详细讲解如何在 UniApp 项目中使用 UView 框架封装一个自定义 Modal 组件,并提供示例代码,方便您快速上手。

1. 创建组件目录

首先,在您的项目中新建一个 components 文件夹,用于存放自定义组件。

在 components 文件夹下新建一个 modal 文件夹,用于存放自定义 Modal 组件。

2. 创建 Modal 组件文件

在 modal 文件夹中新建一个 modal.vue 文件,用于编写 Modal 组件代码。

3. 引入 UView Modal 组件

在 modal.vue 文件中,引入 UView 的 modal 组件,并在 template 中使用 u-modal 标签。

<template>
  <u-modal :show='show' @close='onCancel' :title='title' :content='content' :show-cancel='showCancel' :cancel-text='cancelText' :show-confirm='showConfirm' :confirm-text='confirmText' @confirm='onConfirm' @cancel='onCancel' />
</template>

4. 定义组件属性和方法

在 script 中,使用 export default 暴露一个组件对象,并在其中定义 props、data、methods 等属性和方法。

<script>
import { modal } from 'uview-ui';

export default {
  name: 'MyModal',
  props: {
    title: String,
    content: String,
    showCancel: Boolean,
    cancelText: String,
    showConfirm: Boolean,
    confirmText: String,
    value: Boolean
  },
  data() {
    return {
      show: false
    }
  },
  methods: {
    onConfirm() {
      this.$emit('confirm');
      this.show = false;
    },
    onCancel() {
      this.$emit('cancel');
      this.show = false;
    }
  },
  watch: {
    value(val) {
      this.show = val;
    }
  }
}
</script>

在 methods 中,定义需要暴露给父组件的方法,例如 confirm、cancel 等。

5. 在父组件中使用自定义 Modal 组件

在父组件中,使用 import 引入自定义 Modal 组件,并在 template 中使用该组件。

<template>
  <view>
    <my-modal v-model='showModal' :title='title' :content='content' :show-cancel='showCancel' :cancel-text='cancelText' :show-confirm='showConfirm' :confirm-text='confirmText' @confirm='onConfirm' @cancel='onCancel' />
  </view>
</template>

6. 绑定显示状态和监听事件

在父组件中,使用 v-model 指令绑定 Modal 的显示状态,并使用 @confirm、@cancel 等事件监听器调用自定义 Modal 组件中的方法。

<script>
import MyModal from '@/components/modal/modal.vue';

export default {
  components: {
    MyModal
  },
  data() {
    return {
      showModal: false,
      title: '提示',
      content: '确定要删除吗?',
      showCancel: true,
      cancelText: '取消',
      showConfirm: true,
      confirmText: '确定'
    }
  },
  methods: {
    onConfirm() {
      console.log('confirm');
    },
    onCancel() {
      console.log('cancel');
    }
  }
}
</script>

总结

通过以上步骤,您就可以成功封装一个自定义 Modal 组件,并将其应用到您的 UniApp 项目中。您可以根据自己的需求,对组件进行进一步的定制和扩展。

希望本教程能够帮助您更好地理解 UniApp UView 框架下的自定义组件封装,并应用到实际项目开发中。


原文地址: https://www.cveoy.top/t/topic/n7ta 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录