vue 用 import 导入css有什么办法可以解决只显示当前模板的css?

如果用 import '/public/css/home.css' 导入 css,只要访问过的页面,css 就会被保留。

image.png

有什么办法能不保留,只保留当前模板导入的 css

如果是 <style src="/public/css/home.css" scoped></style> 那这个只作用于当前,子组件中用不到,有什么好办法,要的效果就是作用于当前模板和子组件

我现在用得一个笨方法,就是在 routes.js 里面加 styles

    {
        path: '/',
        name: 'home',
        component: HomeView,
        styles: ['/public/css/home.css']
    }

然后

router.beforeEach((to, from, next) => {
    if (to.styles && to.styles.length > 0) {
        to.styles.forEach(val => import(val));

        next();
    } else {
        next();
    }
})

这个方法访问首页的时候样式会后加载,会出现一下没样式,其他页面没问题,不知道为什么

阅读 2.7k
2 个回答
// <script setup lang="ts">
import { onUnmounted, onMounted } from 'vue';
import cssText from '/public/css/home.css?inline';

const style = document.createElement('style');
style.textContent = cssText;
onMounted(() => {
    document.head.append(style);
});
onUnmounted(() => {
    document.head.removeChild(style);
});

没有动态删除这一说,因为没有必要,要不然也不会有那么多种样式隔离的解决方案了。
之前也有人提问过类似的问题可以参考一下:

虽然但是你得先把你的CSS类名规范起来先。或者使用 scope


本文参与了SegmentFault 思否面试闯关挑战赛,欢迎正在阅读的你也加入。
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题