我正在尝试使用 Vue.js,而不需要构建步骤。但 Vue 没有 style 属性。
因此,我想到在我的 Vue 组件实例上创建一个自定义“样式”属性,然后在创建或安装组件时将该属性的内容注入(inject)到 DOM 中。
唯一的问题是我不明白该怎么做。 (我查看了插件文档)。我需要创建某种插件,首先检查“样式”属性是否存在,然后将其插入到 DOM 中。另外我不想使用 Vue.component() 函数,因为我想使用 ES6 导入和导出。结果如下:
// MyComponent.js
export default {
template: `<div>My component</div>`,
style: `
.hello {
background: #ccc;
}
`,
}
// App.js
import MyComponent from './MyComponent.js'
new Vue({
el: '#app',
components: {
MyComponent
}
})
当创建 MyComponent 时,它应该获取“style”属性的值并将其添加到 DOM,如下所示。任何想法将不胜感激。
$('body').append('<style>' + STYLE + '</style>')
这是一个使用 Vue.component() 函数的插件。但我不想使用组件功能。
最佳答案
您可以使用 v-bind:style
来使用计算内联样式或者只是 :style
简而言之。它将把给定的对象映射到正确的 CSS 样式。使用驼峰命名法,即 backgroundColor
而不是background-color
.
如果你想要全局样式,你可以使用 mounted
将样式标签注入(inject)到 head 中。生命周期钩子(Hook)。您应该在 destroyed
中再次删除它。 .
编辑:我误解了你的帖子,更新了答案
var app = new Vue({
el: '#app',
data: {
subject: 'World'
},
computed: {
subjectStyle() {
return {
color: 'yellow',
backgroundColor: 'rebeccapurple',
};
}
},
mounted() {
const css = `
body {
background-color: #eee;
font-family: 'Comic Sans MS', sans-serif;
}
`;
this.styleTag = document.createElement('style');
this.styleTag.appendChild(document.createTextNode(css));
document.head.appendChild(this.styleTag);
},
destroyed() {
this.styleTag.remove();
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
Hello, <span :style="subjectStyle">{{ subject }}</span>!
</div>
下面是一些插件代码,它允许每个 Vue 实例指定一些样式。样式将被注入(inject) <head>
并在组件被销毁时再次删除。
const StylePlugin = {
install(Vue) {
Vue.mixin({
mounted() {
const css = this.$options.style;
if (!css) return;
this.$styleTag = document.createElement('style');
this.$styleTag.appendChild(document.createTextNode(css));
document.head.appendChild(this.$styleTag);
},
destroyed() {
if (this.$styleTag) {
this.$styleTag.remove();
}
}
});
}
};
Vue.use(StylePlugin);
var app = new Vue({
el: '#app',
data: {
subject: 'World'
},
style: `
body {
background-color: rebeccapurple;
color: white;
font-family: 'Comic Sans MS', sans-serif;
}
`,
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
Hello, World
</div>
关于javascript - 如何为 Vue.js 组件创建自定义样式属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56932013/