Vue.js页面垂直分栏问题:如何实现表格全屏显示?
问题排查:页面垂直分栏与表格全屏显示问题
问题描述
使用Vuejs、Pug、Axios、Pinia和Bootstrap成功渲染数据后,页面被垂直分成两部分,经检查主div外无多余div,需要实现表格全屏显示。
相关代码
App.vue
<template lang="pug"> div.container-fluid h1.text-center.m-4.text-danger My Table table.table.table-striped.table-responsive-md thead tr th(:scope="col" style="width: 20%") User ID th(:scope="col") ID th(:scope="col") Title th(:scope="col") Body tbody tr(v-for="post in posts" :key="post.id") td.text-primary {{ post.userId }} td.text-success {{ post.id }} td.text-success {{ post.title }} td.text-primary {{ post.body }} </template> <style> @media (min-width: 1024px) { .table-center { margin: 0 auto; } } </style> <script> import { defineComponent, computed } from 'vue' import axios from 'axios' import { usePostStore } from './store/posts' export default defineComponent({ name: 'App', setup() { const postStore = usePostStore() const fetchPosts = async () => { const response = await axios.get('https://jsonplaceholder.typicode.com/posts') postStore.setPosts(response.data) } fetchPosts() const posts = computed(() => postStore.posts) return { posts } } }) </script>
./store/posts.js
import { defineStore } from 'pinia' import axios from 'axios' export const usePostStore = defineStore({ id: 'post', state: () => ({ posts: [] }), actions: { async fetchPosts() { try { const response = await axios.get('https://jsonplaceholder.typicode.com/posts') this.setPosts(response.data) } catch (error) { console.error(error) } }, setPosts(posts) { this.posts = posts } }, mutations: { setPosts(posts) { this.posts = posts }, }, })
原因分析与解决方案
1. Pug模板语法错误(核心问题)
原App.vue的Pug模板末尾存在多余的</template>标签,这会被浏览器解析为无效DOM元素或文本节点,直接导致页面结构异常,出现垂直分栏。需要删除该标签,Pug采用缩进式语法,无需手动闭合<template>标签。
2. 实现表格全屏显示的调整
- 重置浏览器默认样式:浏览器默认给
body元素设置了margin: 8px,会导致页面四周留白,无法真正全屏。添加全局样式:
body { margin: 0; }
- 强制表格占满宽度:给表格添加Bootstrap的
w-100类,确保表格宽度始终为100%:
table.table.table-striped.table-responsive-md.w-100
- 检查根容器样式:确认Vue挂载的根元素(通常是
#app)没有额外的margin或padding,可添加样式:
#app { margin: 0; padding: 0; }
3. 冗余代码清理
Pinia的defineStore中无需mutations选项,Pinia推荐直接在actions中修改状态,可删除冗余的mutations块简化代码:
import { defineStore } from 'pinia' import axios from 'axios' export const usePostStore = defineStore({ id: 'post', state: () => ({ posts: [] }), actions: { async fetchPosts() { try { const response = await axios.get('https://jsonplaceholder.typicode.com/posts') this.posts = response.data } catch (error) { console.error(error) } }, setPosts(posts) { this.posts = posts } } })
内容的提问来源于stack exchange,提问作者Hazal Kaya
相关产品推荐
相关产品推荐

