vue3 组件内使用路径

本文介绍了在Vite构建过程中遇到的组件路径不被编译的问题,以及如何通过动态导入(import.meta.glob)来解决。在Vue组件中,作者展示了如何在`onMounted`钩子中异步加载图片资源,并利用`useAttrs`获取属性。文章还包含了完整的模板、脚本和样式代码,为Vite项目中处理静态资源提供了一种实践方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

使用vite打包时不能将组件的路径进行编译。通过modules解决

<template>
  <div class="t-img" v-bind="attr">
    <img :src="src?.default" alt="" />
  </div>
</template>

<script lang="ts" setup>
import { defineProps, useAttrs,  ref, onMounted } from "vue";
import type { PropType } from "vue";
const props = defineProps({
  src: {
    type: String as PropType<string>,
    require: true,
    default: "",
  },
});
const modules = import.meta.glob("/src/assets/img/*.png");
const src = ref<any>();
onMounted(async () => {
  src.value = await modules[props.src]();
});
const attr = useAttrs();
</script>

<style lang="scss" scoped>
.t-img {
  position: relative;
  img {
    width: 100%;
    height: 100%;
    position: absolute;
    top: 0;
    right: 0;
  }
}
</style>

Vue3中集成Ant Design的Modal组件并添加内部由,通常是在需要在一个可关闭的弹窗里展示完整的子页面功能时使用。以下是基本步骤: 1. 首先,你需要安装Ant Design VueVue Router库,如果还没安装可以使用`npm install ant-design-vue@latest vue-router@latest`。 2.Vue组件中引入必要的模块: ```javascript import { Modal } from &#39;ant-design-vue&#39;; import { useRouter } from &#39;vue-router&#39;; ``` 3. 创建一个可复用的Modal组件,比如`ModalWithRoute.vue`,这里包含由切换: ```html <template> <Modal v-model="visible" @on-ok="handleOk"> <router-view></router-view> </Modal> </template> <script> export default { name: &#39;ModalWithRoute&#39;, props: { visible: { type: Boolean, default: false, }, }, methods: { handleOk() { // 当点击确认按钮时,关闭Modal并执行由跳转(假设你有一个名为&#39;/detail&#39;的路径) this.$router.push(&#39;/detail&#39;); this.$emit(&#39;ok&#39;, this.$router.currentRoute.fullPath); // 返回当前路径给外部组件 }, }, }; </script> ``` 4. 在需要显示由的父组件使用这个Modal组件,并设置它的可见状态: ```html <template> <button @click="openModal">打开带由的Modal</button> <ModalWithRoute :visible.sync="modalVisible" @ok="handleClose"></ModalWithRoute> </template> <script> import ModalWithRoute from &#39;./components/ModalWithRoute.vue&#39;; export default { components: { ModalWithRoute, }, data() { return { modalVisible: false, }; }, methods: { openModal() { this.modalVisible = true; }, handleClose(path) { this.modalVisible = false; // 关闭Modal // 如果需要,你也可以在这里处理返回的路径 }, }, }; </script> ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值