当前位置:首页 > 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)增强灵活性

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

使用vue实现页面复用

<!-- 子组件 -->
<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('复用逻辑');
    }
  }
}

在组件中引入:

使用vue实现页面复用

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 Router 的编程式导航 通过 this.$route…

vue实现两个登录页面

vue实现两个登录页面

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

vue实现页面定位

vue实现页面定位

Vue 实现页面定位的方法 在 Vue 中实现页面定位通常可以通过以下几种方式完成,包括使用原生 JavaScript 的 scrollIntoView 方法、Vue Router 的滚动行为配置,以…

vue实现页面缓存

vue实现页面缓存

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

css制作锁屏页面

css制作锁屏页面

使用CSS制作锁屏页面 锁屏页面通常包含一个背景、时间显示以及可能的解锁按钮或输入框。以下是实现锁屏页面的关键CSS代码和结构。 HTML结构 <!DOCTYPE html> <…

css制作音乐盒页面

css制作音乐盒页面

音乐盒页面设计思路 音乐盒页面通常需要结合音频播放功能与视觉设计。以下是实现一个基础音乐盒页面的关键步骤。 HTML结构搭建 基础HTML需包含音频播放器控件和播放列表: <!DOC…