【发布时间】:2021-09-23 03:58:59
【问题描述】:
我创建了以下 Vue 组件:
var loading = new Vue({
el: "#loading_id",
components:{
'loading' : {
template : `
<div>
<div id="screenLoading" class="background">
<div class="loading">
<div class="obj"></div>
<div class="obj"></div>
<div class="obj"></div>
<div class="obj"></div>
<div class="obj"></div>
<div class="obj"></div>
<div class="obj"></div>
<div class="obj"></div>
</div>
</div>
</div>
`,
methods: {
startLoading: function() {
const load = document.getElementById("screenLoading");
load.classList.add('show')
},
stopLoading: function(){
const load = document.getElementById("screenLoading");
load.classList.remove('show')
}
}
}
}
});
loading.$children[0].startLoading()
setTimeout(() => {
loading.$children[0].stopLoading()
}, 3500);
.background {
width: 100vw;
height: 100vh;
background: rgba(0, 0, 0,.5);
position: fixed;
top: 0px;
left: 0px;
z-index: 2000;
display: none;
justify-content: center;
align-items: center;
}
.background.show {
display: flex;
}
.loading{
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
height: 40px;
display: flex;
align-items: center;
}
.obj{
width: 12px;
height: 70px;
background: white;
margin: 0 3px;
border-radius: 10px;
animation: loading 0.8s infinite;
}
.obj:nth-child(2){
animation-delay: 0.1s;
}
.obj:nth-child(3){
animation-delay: 0.2s;
}
.obj:nth-child(4){
animation-delay: 0.3s;
}
.obj:nth-child(5){
animation-delay: 0.4s;
}
.obj:nth-child(6){
animation-delay: 0.5s;
}
.obj:nth-child(7){
animation-delay: 0.6s;
}
.obj:nth-child(8){
animation-delay: 0.7s;
}
@keyframes loading{
0%{
height: 0;
}
50%{
height: 70px;
}
100%{
height: 0;
}
}
<script src="https://cdn.jsdelivr.net/npm/vue"></script>
<loading id="loading_id"></loading>
它工作得很好,它的目的是当我不得不在我的网页上等待某些东西时,它是一个加载屏幕供我使用。但是,我不想从带有主 HTML 上的 <style> 标签的外部 CSS 文件加载 CSS,而是直接从 Vue 内部加载我的 CSS,就像我在 template 变量上处理 HTML 一样。基本上,它会是这样的:
var loading = new Vue({
el: "#loading_id",
components:{
'loading' : {
template : `myHTML template`,
cssTemplate: `myCSS template`,
methods: {
// my methods
}
}
}
});
可以在 Vue 上做吗?我可以在 Vue 组件中编写 CSS 模板吗?
我知道我也可以使用 Vue 加载小块 CSS 样式,如 here 所述,但在我的情况下,我想保留类和 ids 声明,就像它们在普通 CSS 文件中一样...
【问题讨论】:
-
是的。它被称为单文件组件,您需要依赖捆绑器来正确编译文件。 vuejs.org/v2/guide/single-file-components.html
-
SFC 是自 v2.0 起使用 Vue 的推荐方式。您现在正在做的是一种有局限性的解决方法。
标签: vue.js