当前位置:首页 > VUE

使用vue实现页面复用

2026-01-22 01:25:09VUE

使用组件化实现复用

Vue的核心思想是组件化,通过将页面拆分为独立组件实现复用。创建可复用的.vue文件,包含模板、脚本和样式:

<template>
  <div class="reusable-component">
    <h3>{{ title }}</h3>
    <slot></slot>
  </div>
</template>

<script>
export default {
  props: ['title']
}
</script>

在其他页面通过import引入并注册组件,通过<template>标签直接使用。

利用插槽(Slot)增强灵活性

通过默认插槽或具名插槽允许父组件定制子组件内容:

<!-- 子组件 -->
<template>
  <div>
    <slot name="header"></slot>
    <slot></slot>
  </div>
</template>

<!-- 父组件 -->
<reusable-component>
  <template v-slot:header>
    <h2>自定义标题</h2>
  </template>
  <p>自定义内容</p>
</reusable-component>

通过混入(Mixin)共享逻辑

定义混入对象mixin.js

export const reusableMixin = {
  methods: {
    sharedMethod() {
      console.log('复用逻辑');
    }
  }
}

在组件中引入:

import { reusableMixin } from './mixin.js';
export default {
  mixins: [reusableMixin]
}

动态组件按需加载

使用<component :is="">动态切换组件:

<template>
  <component :is="currentComponent"></component>
</template>

<script>
import ComponentA from './ComponentA.vue';
import ComponentB from './ComponentB.vue';
export default {
  data() {
    return {
      currentComponent: 'ComponentA'
    }
  },
  components: { ComponentA, ComponentB }
}
</script>

高阶组件(HOC)模式

通过函数返回增强后的组件:

function withReusableLogic(WrappedComponent) {
  return {
    mounted() {
      console.log('增强逻辑');
    },
    render(h) {
      return h(WrappedComponent, this.$attrs);
    }
  }
}

路由参数复用同一组件

vue-router中配置动态路由,通过watch监听参数变化:

const routes = [
  { path: '/page/:id', component: ReusablePage }
];

// 组件内
watch: {
  '$route.params.id'(newId) {
    this.loadData(newId);
  }
}

使用vue实现页面复用

标签: 复用页面
分享给朋友:

相关文章

vue如何实现默认页面

vue如何实现默认页面

实现 Vue 默认页面的方法 在 Vue 中实现默认页面通常涉及路由配置。以下是几种常见的方法: 使用路由重定向 在 Vue Router 配置中,可以通过 redirect 属性设置默认路由:…

vue实现两个登录页面

vue实现两个登录页面

实现两个登录页面的方法 在Vue中实现两个不同的登录页面,可以通过路由配置和组件分离来完成。以下是具体实现步骤: 配置路由 在router/index.js文件中定义两个不同的路由路径,分别指向不…

vue实现引导页面

vue实现引导页面

vue实现引导页面的方法 使用Vue实现引导页面可以通过多种方式完成,以下是几种常见的方法: 使用第三方库driver.js 安装driver.js库: npm install drive…

vue实现页面缓存

vue实现页面缓存

使用 <keep-alive> 组件实现缓存 Vue 内置的 <keep-alive> 组件可以缓存动态组件或路由组件。通过包裹需要缓存的组件,可以保留其状态避免重复渲染。…

vue实现预约页面

vue实现预约页面

实现预约页面的基本结构 使用Vue CLI或Vite创建一个新项目,安装必要依赖如vue-router和axios。项目结构建议包含components文件夹存放可复用组件,views文件夹存放页面级…

vue实现组织架构页面

vue实现组织架构页面

Vue 实现组织架构页面 数据准备 组织架构通常以树形结构展示,需要准备嵌套的节点数据。例如: data() { return { orgData: { id: 1,…