javascript - 如何在 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 组件样式中的所有数据?
多谢你们
解决方案
有,但你需要使用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'
]
}
]
}
推荐阅读
- python - 如何擦除控制台输出的最后一个字符?
- python - 关于图像识别 cnn 应该在预测中返回什么的一些说明
- python - 我正在尝试解析所有页面的数据。只解析第一页
- android-studio - 如何在 Android Studio 中启用自动格式化 Flutter 项目?
- vee-validate - VeeValidate 3.1 未显示错误
- javascript - 未捕获的类型错误:无法读取 null 的属性“uid”
- python - 从大表中获取时,asyncpg.Cursor.fetch() 非常慢
- android - 清单属性在哪个生命周期方法中应用于活动?那些是从其他扩展活动继承而来的吗?
- php - 找不到类'Magento\Framework\App\Action\Action'
- python - 试图创建说话人识别神经网络,但不幸的是我的神经网络准确率很低