能否通过Props修改Layout内容?Vue布局标题动态化需求
用Props实现Layout组件动态修改h1文本
直接通过给Layout组件添加Props就能实现需求,步骤如下:
1. 修改Layout组件,添加Props接收标题
给Layout组件定义一个接收标题的Props,然后把h1的内容替换为这个Props的值:
<template> ...navigation for all pages.. <h1>{{ pageTitle }}</h1> <slot /> ...footer for all pages... </template> <script setup> // 定义Props,指定类型和可选配置 defineProps({ pageTitle: { type: String, required: true, // 强制每个页面都传标题,也可以设为false并加default给默认值 // default: '默认页面标题' // 可选,当页面没传标题时显示这个内容 } }) </script>
2. 在页面组件中传递标题Props
在各个页面使用Layout时,通过属性传递对应的标题文本:
pages/index.vue
<template> <Layout page-title="首页"> index is here ok :) </Layout> </template> <script setup> import Layout from '@/components/Layout.vue' // 请根据你的实际文件路径调整 </script>
pages/about.vue
<template> <Layout page-title="关于我们"> about is here ok :) </Layout> </template> <script setup> import Layout from '@/components/Layout.vue' </script>
这样就能让不同页面使用同一个Layout时,渲染各自的h1文本,不用重复编写h1和中间的公共内容。
内容的提问来源于stack exchange,提问作者Jarder
相关产品推荐
相关产品推荐

