Reputation: 929
After I make an API call, I want to create elements according to the response. I want the background color of the span be determined by the response I get. I create the span elements like this:
<span v-else class="a" v-bind:style="determineColorOfLine(response)">
{{ response }}
And I have a function called determineColorOfLine inside of methods
determineColorOfLine(response){
console.log(response)
return ("background-color: " + response)
}
I expect to see the text "response" with the background color of the API request's response (e.g. "blue"). However, the background color does not change. When I inspect the span element, I see
style=""
but I would expect
style="background-color: blue"
In the console, I see the log "blue", so the method gets run. I don't see any errors. Where is the error.
Upvotes: 0
Views: 553
Reputation: 1061
Use computed property
computed: {
colorOfLine() {
return { backgroundColor: this.response }
}
}
<span :style="colorOfLine"...
If your response
comes from a parent component, create a nested component for your span
and pass response
as a prop.
ParentComponent.vue
<template>
<div v-for="(response, ind) in request.responses"
class="is-inline-block" :key="ind">
<MyCustomSpan :response="response" />
</div>
</template>
<script>
import MyCustomSpan from './MyCustomSpan.vue';
export default {
inject: [ 'myService' ],
data() {
return {
responses: []
}
},
async mounted() {
this.responses = await this.myService.getResponses();
},
components: {
'MyCustomSpan': MyCustomSpan
}
}
</script>
MyCustomSpan.vue
<template>
<span v-else class="a" :style="colorOfLine">
{{ response }}
</span>
</template>
<script>
export default {
props: [ 'response' ],
data() {
return {
}
},
mounted() {
},
computed: {
colorOfLine() {
return { backgroundColor: this.response }
}
}
}
</script>
Upvotes: 1
Reputation: 11447
You need to return an object:
determineColorOfLine(response){
console.log(response)
// Make an object here
return {"background-color": response}
}
Upvotes: 1
Reputation: 14689
You're returning style="background-color: blue"
and binding it to the inline style in effect creating the statement style=style="background-color: blue"
Instead, use return 'background-color: ' + response;
Upvotes: 2