I'm trying to bind the src
attribute to a variable managed by Vuex
, so I did:
<img
class="navbar-brand-item"
v-bind:src="{ 'assets/images/logo-light.png' : isNavbarLight, 'assets/images/logo.png' : !isNavbarLight }"
alt="Logo"
/>
the variable isNavbarLight
is taken from the Vuex
store:
<script lang="ts">
import { defineComponent, computed } from 'vue'
import { useStore } from 'vuex'
export default defineComponent({
name: 'Header',
setup() {
const store = useStore()
const isNavbarLight = computed(() => store.state.isNavbarLight)
return {
isNavbarLight
}
}
})
</script>
and it's a boolean
variable which allow me to change the type of logo based on the page color. This is the Vuex
store implementation:
import { Commit, createStore } from 'vuex';
export default createStore({
state: {
isNavbarLight: false
},
mutations: {
setNavbarLight: (state: {isNavbarLight: boolean}, value: boolean) => state.isNavbarLight = value
},
actions: {
setNavbarLight: ({commit}: {commit: Commit}, value: boolean) => commit('setNavbarLight', value)
},
modules: {}
});
The issue is that as final result I get:
<img class="navbar-brand-item" src="[object Object]" alt="Logo">
how is that possible?
Of course it's possible, but right now you are trying to bind it to an object that has two boolean properties!
<img
class="navbar-brand-item"
v-bind:src="isNavbarLight ? 'assets/images/logo-light.png' : 'assets/images/logo.png'"
alt="Logo"
/>
This is how you can use a statement with a ternary operator to switch between the two image URLs, or you could use a computed property or a value from the Vuex store, as long as it returns a string, because that's what the src
attribute requires.