Vue中能否将img的:src绑定至变量?绑定Vuex变量时出现[object Object]异常求助
[object Object] Hey there! Let's break down why your image source is showing up as [object Object] instead of the correct logo path, and how to fix it.
The Root Cause
You're using object syntax to bind the src attribute, like this:
<img :src="{ 'assets/images/logo-light.png' : isNavbarLight, 'assets/images/logo.png' : !isNavbarLight }" />
But the src attribute expects a single string value, not an object. Vue doesn't interpret this object as a conditional picker—it just converts the entire object to a string, which results in [object Object]. That's exactly what you're seeing in the rendered HTML.
Simple Fixes
There are two clean ways to handle this conditional image binding:
1. Use a Ternary Expression in the Template
This is the most straightforward approach for simple conditional logic:
<img class="navbar-brand-item" :src="isNavbarLight ? 'assets/images/logo-light.png' : 'assets/images/logo.png'" alt="Logo" />
The ternary checks isNavbarLight and returns the correct path string directly.
2. Use a Computed Property (Better for Reusability)
If you might reuse this logic elsewhere, or if the conditional gets more complex, a computed property is cleaner. Update your component's setup function:
import { defineComponent, computed } from 'vue' import { useStore } from 'vuex' export default defineComponent({ name: 'Header', setup() { const store = useStore() const isNavbarLight = computed(() => store.state.isNavbarLight) // Add this computed property const logoSrc = computed(() => { return isNavbarLight.value ? 'assets/images/logo-light.png' : 'assets/images/logo.png' }) return { logoSrc } } })
Then reference it in your template:
<img class="navbar-brand-item" :src="logoSrc" alt="Logo" />
Quick Check on Your Other Code
Your Vuex setup looks solid—you're correctly using a computed property to pull isNavbarLight from the store, so as long as that state updates properly (via the setNavbarLight mutation/action), your image source will switch automatically. Just double-check that your image paths match your project's static asset structure (e.g., if you're using Vite, you might need to prefix paths with / like /assets/images/logo.png).
内容的提问来源于stack exchange,提问作者sfarzoso

