使用 VueJS 动态编辑内联 CSS
Dynamically Edit Inline CSS with VueJS
如何使用 VueJS 更改标签的属性?我正在尝试制作一个单页应用程序,其背景每次从后端获取数据时都会发生变化。我试过使用 v-bind:style
和 v-style
但都以 "breaking" Vue.有没有一种方法可以让我像在本机 JS 中那样编写一个方法来更改 DOM?我也尝试过实现 document.getElementbyId
等等,但它也破坏了 VueJS。
换句话说,我该如何做 background-image: {{pic_url}};
抱歉在移动设备上格式化。
我在实现此功能时遇到了一些麻烦,因为内联样式周围有引号,然后 'url("")'
中还有两组引号。当我将样式对象拉出到它自己的对象中时,我让它工作了:
https://jsfiddle.net/ahwLc3rq/
html
<div id="app">
<div id="test" :style="backgroundStyle"></div>
</div>
js
new Vue({
el:'#app',
data:function(){
return {
pic_url: 'https://anchormetrics.com/wp-content/themes/bootstrap-basic-child/images/amlogo.png'
}
},
computed:{
backgroundStyle:function(){
return {
'background-image':'url("'+this.pic_url+'")'
}
}
},
methods:{
fetchPic:function(){
this.$http.get('/path/to/api').then(function(response){
this.pic_url = response;
}.bind(this))
}
},
ready:function(){
this.fetchPic();
}
});
如何使用 VueJS 更改标签的属性?我正在尝试制作一个单页应用程序,其背景每次从后端获取数据时都会发生变化。我试过使用 v-bind:style
和 v-style
但都以 "breaking" Vue.有没有一种方法可以让我像在本机 JS 中那样编写一个方法来更改 DOM?我也尝试过实现 document.getElementbyId
等等,但它也破坏了 VueJS。
换句话说,我该如何做 background-image: {{pic_url}};
抱歉在移动设备上格式化。
我在实现此功能时遇到了一些麻烦,因为内联样式周围有引号,然后 'url("")'
中还有两组引号。当我将样式对象拉出到它自己的对象中时,我让它工作了:
https://jsfiddle.net/ahwLc3rq/
html
<div id="app">
<div id="test" :style="backgroundStyle"></div>
</div>
js
new Vue({
el:'#app',
data:function(){
return {
pic_url: 'https://anchormetrics.com/wp-content/themes/bootstrap-basic-child/images/amlogo.png'
}
},
computed:{
backgroundStyle:function(){
return {
'background-image':'url("'+this.pic_url+'")'
}
}
},
methods:{
fetchPic:function(){
this.$http.get('/path/to/api').then(function(response){
this.pic_url = response;
}.bind(this))
}
},
ready:function(){
this.fetchPic();
}
});