您的位置:首页 > 科技 > IT业 > vue中封装组件实例

vue中封装组件实例

2024/7/4 6:22:18 来源:https://blog.csdn.net/qingdouxiaohua/article/details/139237324  浏览:    关键词:vue中封装组件实例

本篇是一篇组件封装。因为要经常使用,特此封装并且记录下来,以供参考。

封装组件:封装组件是指将一段具有特定功能的Vue代码(包括模板、脚本和样式)封装成一个可复用的组件。这个组件可以作为一个独立的单元,在多个地方被引用和使用。封装组件的主要目的是为了代码的复用和可维护性。在封装组件时,我们通常会定义props(属性)来接收外部传入的数据,定义events(事件)来向外部发送数据,以及定义slots(插槽)来让外部可以自定义组件的某部分内容。

创建目录:


封装子组件:

<style scoped>
/* 顶部 */
.box {background-color: #f4f4f4;width: 100%;height: 500px;
}
.top {width: 100%;display: flex;justify-content: space-around;align-items: center;height: 40px;/* position: fixed;top: 0;right: 0; *//* text-align: center; */background-color: white;
}.button {width: 70px;display: flex;justify-content: space-between;align-items: center;background-color: white;border: 1px solid;border-radius: 20px;
}.backspacing {width: 20px;height: 20px;
}.null {width: 70px;
}
</style>
<template><!-- 顶部导航栏 --><div class="top"><button class="button"><img src="../assets/zuoz.png" alt="" class="backspacing" @click="BACK" /><span>|</span><imgsrc="../assets/home2.png"@click="homes"alt=""class="backspacing"/></button><div class="text">{{ text }}</div><div class="null"></div></div>
</template><script setup>
import { ref, computed, watch, reactive } from "vue";
import axios from "axios";
import { useRouter } from "vue-router";
import { useRoute } from "vue-router";
const props = defineProps(["text"]);const router = useRouter();
const route = useRoute();
// 返回我的页面
const BACK = () => {router.push({name: "Mine",});
};// 返回首页
const homes = () => {router.push({path: "/Home",});
};
</script>

在封装的组件当中,你可以把它所有的事件也都可以放进去,
定义了一个名为 text 的 prop,并在模板中使用 {{ text }} 来显示它,它可以接收外部传入的数据(通过 props)并展示它。

父组件:

<style  scoped>
</style><template><div><top text="收益"> </top></div>
</template><script setup>
import top from "../components/top.vue";
import { ref, computed, watch, reactive } from "vue";
import axios from "axios";
import { useRouter } from "vue-router";
import { useRoute } from "vue-router";
const router = useRouter();
const route = useRoute();
</script>

父组件中,导入了 top 组件,并在模板中使用了它。通过 text="收益" 向子组件传递了一个 prop 值。这就是父子组件之间传值的一个例子。
 

总结

  • 封装组件top.vue 是一个封装的组件,因为它可以接收外部数据(通过 props)并展示它。
  • 父子组件之间传值:在父组件中,通过 text prop 将数据传递到 top 子组件中,这体现了父子组件之间的数据传递。

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com