You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue中能否将img的:src绑定至变量?绑定Vuex变量时出现[object Object]异常求助

Why Your Vue img src is Rendering as [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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 23:17:51