在SFC中增加<style js>语法 #516
Replies: 0 comments 6 replies
-
Translate to English: What problem does this feature solve? The current <style scope> works well in most cases, but not in these two situations:
What does the proposed API look like? There is a solution in the current code, which is to use v-bind:style and then set the component's style in the JS code. If we extend this solution, we can get a more versatile solution, which is <style js>. The styles written here will be encoded as JS code and then bound to the element via v-bind:style. This perfectly solves the two problems mentioned earlier, I no longer need to import CSS, and I also get perfect component style isolation. |
Beta Was this translation helpful? Give feedback.
-
你说的这个不成立,这个和是 React 还是 Vue 毫无关系,这个取决于组件发布时是怎么编译打包的。 |
Beta Was this translation helpful? Give feedback.
-
确实如此,但是同样也要考虑不同框架的编码习惯 对于React,典型的代码如下: function MyComponent() {
const style = {
color: 'red',
fontSize: '20px',
};
return (
<div style={style}>
Hello, world!
</div>
);
} 但是对于vue,典型的代码如下: <template>
<div class="class1">
Hello, world!
</div>
</template>
<style scope>
.class1 {
color: red;
fontSize: 20px;
}
</style> 在这样的情况下,React内联了样式,而Vue使用了独立的CSS文件 |
Beta Was this translation helpful? Give feedback.
-
React 下也有可以抽离出静态 CSS 文件的方案,Vue 组件的样式文件也可以编译成 JS 模块输出,这也不是写法习惯的问题。 |
Beta Was this translation helpful? Give feedback.
-
为什么不这么做? |
Beta Was this translation helpful? Give feedback.
-
感觉你说的是这种 @tianxiadys <script setup>
import { ref } from 'vue'
const msg = ref('Hello World!')
</script>
<script>
const style = {
color: 'red',
fontSize: '20px',
}
</script>
<template>
<h1 :style="style">{{ msg }}</h1>
<input v-model="msg">
</template> |
Beta Was this translation helpful? Give feedback.
-
What problem does this feature solve?
现在的<style scope>在大多数情况下运转良好,但是在这两种情况下不行:
1、需要作为第三方库导出的vue组件。对于react,我只需要在项目中导入第三方库的js文件即可,但是对于vue,我还需要导入css。
2、在组件边界,相同的类名并不能完全的隔离,如果父子组件都具有相同的class名称,则对于这个相同的class的样式隔离会失效。
What does the proposed API look like?
在现有的代码中,有一个解决方案,那就是通过v-bind:style,然后在js代码中设置组件的样式。
如果我们扩展这个方案,可以得到一个通用性更强的方案,那就是<style js>,书写在这里的样式将被编码为js代码,然后通过v-bind:style绑定到元素上。这完美的解决了刚刚提到的两个问题,我不再需要导入css,我也得到了完美的组件样式隔离
Beta Was this translation helpful? Give feedback.
All reactions