vue 自定义组件 创建及其使用
发布日期:2021-05-07 15:55:20 浏览次数:14 分类:原创文章

本文共 2267 字,大约阅读时间需要 7 分钟。

vue 自定义组件 创建及其使用


1.vue 自定义组件有全局注册和局部注册两种方式;


全局注册通过 Vue.component 来创建组件,这些组件是全局注册的。也就是说它们在注册之后可以用在任何新创建的 Vue 根实例 (new Vue) 的模板中;


全局注册所有的组件意味着即便你已经不在使用一个组件了,它任然会包含在你最终的构建结果中,这造成了用户现在的JavaScript 的无谓增加。


2.自定义组件局部注册


2.1 创建 组件名.vue 文件,编写组件内容;如果组件还包括其他组件,可创建以该组件名命名的文件夹,并创建index.vue


2.2 使用 在使用自定义组件时 需通过 import 导入,并在父组件 components 中定义;


3. 自定义组件举例


3.1项目文件结构


在这里插入图片描述
这里自定义了两个组件,分别是aside 和header ,对应网页的头部和左侧菜单部分;前端vue 引用 element-ui 桌面组件库;


layout 为前端网页布局定义,网页布局所需组件 全部存放在components文件夹下;


3.2 个组件内容定义


headers/index.vue 文件内容:


<template>    <el-row>        <el-col :span="6">            <div>                <p>这是左侧部分</p>            </div>        </el-col>        <el-col :span="6" class="headerRight">            <div>                 <el-button type="primary" @click="loginOut">退出</el-button>            </div>                </el-col>            </el-row></template><script>export default {
data(){
return {
} }, methods:{
loginOut(){
this.$message('这是一条消息提示'); } }}</script><style scoped>.headerContainer{
display: inline;}.headerLeft{
background-color: blue;}.headerRight{
height: 100%; float: right; }.headerRight div{
height: 100%; margin-top: 10px; text-align: right;}</style>

asides/index.vue 文件内容:


<template>    <p>这是aside 组件</p></template><script>export default {
}</script>

3.3 自定义组件使用:


layout/index.vue 加载 自定义组件 headers 和 asides :


<template>    <div class="layout">            <el-container class="contain-body">            <el-aside >                <asides/>            </el-aside>            <el-container>                <el-header>                    <headers/>                </el-header>                <el-main>main</el-main>            </el-container>        </el-container>    </div></template><script>import headers from './components/headers'import asides from './components/asides'export default {
name: 'Layout', components: {
headers, asides, }}</script><style lang='scss' scoped>.layout{
height: 100%;}.contain-body{
height: 100%;}.el-header{
background-color: #b3c0d1;}.el-main {
background-color: #E9EEF3; color: #333; text-align: center; line-height: 160px;}</style>

3.4 最终页面效果:


在这里插入图片描述

上一篇:vue项目配置文件vue.config.js中devServer.proxy 使用说明
下一篇:你可能不知道的Linux实时机制,dl_sched_class,死了都要Run

发表评论

最新留言

逛到本站,mark一下
[***.202.152.39]2025年03月26日 10时47分00秒