是否可以在Vue.js中有条件地导入CSS文件? [英] Is it possible to import css file conditionally in Vue.js?

查看:564
本文介绍了是否可以在Vue.js中有条件地导入CSS文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在一个 Vue.js项目中有自己的管理面板和客户页面.仅当当前路由具有"forAdmin" 元数据时,才可以使用某些 css文件吗?

I have my admin-panel and pages for clients in one Vue.js project. Is it possible to use certain css-files only if the current route has "forAdmin" meta?

推荐答案

通过将 style-loader

By using style-loader with the useable API, you can dynamically apply and remove a stylesheet in your code.

首先,您需要更新Webpack配置规则,以便使用 useable API加载扩展名为 .useable.css 的样式表:

First you'll need to update your webpack config rules so that stylesheets with the .useable.css extension will be loaded with the useable API:

{
  test: /\.css$/,
  exclude: /\.useable.css$/,
  use: [
    'style-loader',
    'css-loader'
  ]
},
{
  test: /\.useable\.css$/,
  use: [
    'style-loader/useable',
    'css-loader'
  ]
}

现在在路由器代码文件中,您可以根据自己的条件导入样式表并 .use() .unuse():

Now in your router code file, you can import your stylesheet and .use() and .unuse() it according to your condition:

import style from './admin.useable.css'

const router = new VueRouter(...)

router.afterEach((to, from) => {
  for (const route of to.matched) {
    if (route.meta.forAdmin) {
      style.use()
    }
  }

  for (const route of from.matched) {
    if (route.meta.forAdmin) {
      style.unuse()
    }
  }
})

确保正确平衡 .use() .unuse()调用的总数,因为在后台会保留一个引用计数,以找出何时样式表应被应用.

Make sure you balance the total number of .use() and .unuse() calls correctly because a reference count is maintained behind the scenes to figure out when the stylesheet should be applied.

我不确定您的设置是什么,因此可能会有更好的方法来做您想要的事情.

I'm not sure what your setup is, so there might be a better way of doing what you want though.

这篇关于是否可以在Vue.js中有条件地导入CSS文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆