如何在 VueJS SFC 中使用 JavaScript 访问样式定义?

Posted

技术标签:

【中文标题】如何在 VueJS SFC 中使用 JavaScript 访问样式定义?【英文标题】:How to access style definitions with JavaScript in VueJS SFCs? 【发布时间】:2019-01-26 16:56:55 【问题描述】:

我正在做一个应用程序,我需要在 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 组件中样式内的所有数据?

谢谢各位

【问题讨论】:

您的意思是要在变量中获取的 css 样式吗?或者您想从组件中设置 html 样式 我想得到 里面的所有css 我很好奇为什么需要提取style 标签?编译后的(如果使用scoped会加上[data...],还是哪个版本??我不相信这是可能的,甚至是不希望的。 @Xan 如果我的回答解决了你的赏金问题,请手动奖励赏金,因为原作者最后一次出现在 11 个月前... 【参考方案1】:

在jQuery中,你可以这样做

var color = $(".wrapper__button").css("background-color"));

获取所有的 css 属性。 (你需要做一些字符串操作)

var color = $(".wrapper__button").attr('style');

这是一个工作示例 https://jsfiddle.net/kLpv30dz/

【讨论】:

我想获取 中的所有 css,而不仅仅是背景颜色【参考方案2】:

这个答案与 vue 有所不同,但您可以使用 document.styleSheets 使用 JavaScript 提取 CSS

for (var i=0; i < document.styleSheets.length; i++)
  var styleSheet = document.styleSheets[i];
  console.log(styleSheet);
.wrapper
  color: red;
&lt;div class=".wrapper"&gt;&lt;/div&gt;

【讨论】:

这似乎是我正在寻找的东西,但是如果我有很多组件,我如何区分不同的组件样式以获得所需的样式? 我不这么认为,因为它会给出页面上使用的所有样式表,而不是组件。【参考方案3】:

有,但需要使用CSS modules。

Vue Loader 的文档对usage examples 有更详细的介绍:

<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 的文档还显示了 how to use both the Scoped CSS and 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'
      ]
    
  ]

【讨论】:

以上是关于如何在 VueJS SFC 中使用 JavaScript 访问样式定义?的主要内容,如果未能解决你的问题,请参考以下文章

可以在呈现的 html 中使用带有模板的 VueJS SFC 组件吗?

vue单文件(sfc)编译为js的流程

如何在 Vue SFC 中使用外部模块?

PLC中SFC、SFB如何使用?

Vuejs 中从子级到父级的事件监听

如何在 <script setup> vue SFC 中访问“this”关键字