我为 vue 3 设置了一些演示代码,用于将内联样式更新为计算对象,但它没有更新。
<!DOCTYPE html>
<html>
<head>
<title>Demo</title>
<link rel="stylesheet" href="main.css">
<script src="https://cdn.jsdelivr.net/npm/<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="afd9dacaef9c819d819d99" rel="noreferrer noopener nofollow">[email protected]</a>/dist/vue.global.prod.min.js"></script>
</head>
<body>
<div id="map">
<div id="infantry" class="unit" :style="style">
Position: {{ x }} {{ y }}
</div>
</div>
<script>
const Infantry = {
data() {
return {
x: 0,
y: 0
}
},
mounted() {
setInterval(() => {
this.x++;
this.y++;
}, 1000);
},
computed : {
style() {
return {
top : this.x
};
}
}
}
Vue.createApp(Infantry).mount('#infantry');
</script>
</body>
</html>
这部分不起作用
:style="style"
我检查了 dom,它没有设置使用 top
的样式。有谁知道出了什么问题吗?
最佳答案
问题是您绑定(bind)了挂载 vue 应用程序的元素的属性,然后将 px
添加到返回的顶部值:
.unit {
position: absolute
}
<!DOCTYPE html>
<html>
<head>
<title>Demo</title>
<link rel="stylesheet" href="main.css">
<script src="https://cdn.jsdelivr.net/npm/<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ccbab9a98cffe2fee2fefa" rel="noreferrer noopener nofollow">[email protected]</a>/dist/vue.global.prod.min.js"></script>
</head>
<body>
<div id="map">
<div class="unit" :style="style">
Position: {{ x }} {{ y }}
</div>
</div>
<script>
const Infantry = {
data() {
return {
x: 0,
y: 0
}
},
mounted() {
setInterval(() => {
this.x++;
this.y++;
}, 1000);
},
computed: {
style() {
return {
top: this.x + "px"
};
}
}
}
Vue.createApp(Infantry).mount('#map');
</script>
</body>
</html>
关于javascript - Vue 3 不更新内联样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70536422/