首页 > 解决方案 > 如何在 VueJS SFC 中使用 JavaScript 访问样式定义?

问题描述

我正在做一个应用程序,我需要在 Vue JS 的单个文件组件中提取样式标记内的 CSS。

所以我有这个基本模板:

<template>
  <div class="wrapper">
    <button class="wrapper__button" @click="sendRequest()" click me></button>
  </div>
</template>

<script>
export default {
  name: 'HelloWorld',
  data () {
    return {
      msg: 'Welcome to Your Vue.js App'
    }
  },
  methods: {
    sendRequest () {
      console.log(document.getElementsByTagName("STYLE")[0].innerHTML)
      this.$http.post('http://localhost:3000/users/pdf', 'random string').then((response) => {
        console.log(response.data)
      })
    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style>
.wrapper__button {
  background-color: yellow;
}
</style>

有没有一种方法可以使用 Javascript 获取 vue 组件样式中的所有数据?

多谢你们

标签: javascriptcssvue.jssassvue-loader

解决方案


有,但你需要使用CSS 模块

Vue Loader 的文档更详细地介绍了使用示例

<style module>
.red {
  color: red;
}
.bold {
  font-weight: bold;
}
</style>

<template>
  <p :class="$style.red">
    This should be red
  </p>
</template>

<script>
export default {
  created () {
    console.log(this.$style.red)
    // -> "red_1VyoJ-uZ"
    // an identifier generated based on filename and className.
  }
}
</script>

Vue Loader 的文档还展示了如何将 Scoped CSS 和 CSS Modules与这种 Webpack 配置一起使用:

{
  test: /\.css$/,
  oneOf: [
    // this matches `<style module>`
    {
      resourceQuery: /module/,
      use: [
        'vue-style-loader',
        {
          loader: 'css-loader',
          options: {
            modules: true,
            localIdentName: '[local]_[hash:base64:5]'
          }
        }
      ]
    },
    // this matches plain `<style>` or `<style scoped>`
    {
      use: [
        'vue-style-loader',
        'css-loader'
      ]
    }
  ]
}

推荐阅读