当前位置:首页 > 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 中修改页面属性可以通过多种方式实现,以下是一些常见的方法: 使用 data 属性 在 Vue 组件中,可以通过 data 选项定义页面属性,并在模板或方法…

php实现页面跳转

php实现页面跳转

PHP 页面跳转方法 在 PHP 中,可以通过多种方式实现页面跳转,以下是几种常见的方法: 使用 header() 函数 header() 函数是 PHP 中最常用的跳转方法,通过发送 HTTP 头…

vue 实现页面返回

vue 实现页面返回

监听浏览器返回事件 使用 window.addEventListener 监听 popstate 事件,在 Vue 的 mounted 钩子中绑定事件,并在 beforeDestroy 钩子中移除监听…

jquery页面跳转

jquery页面跳转

jQuery 页面跳转方法 使用 jQuery 实现页面跳转可以通过多种方式完成,以下是几种常见的方法: 使用 window.location.href 通过修改 window.location.h…

Vue实现lagger页面

Vue实现lagger页面

Vue实现懒加载页面的方法 懒加载(Lazy Loading)是一种优化技术,用于延迟加载非关键资源,从而提升页面初始加载速度。在Vue中可以通过以下方式实现懒加载: 路由懒加载 使用Vue Rou…

实现js页面跳转

实现js页面跳转

使用 window.location.href 通过修改 window.location.href 属性实现跳转,这是最常用的方法: window.location.href = "https://…