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

Angular2中如何使HTML绑定的getImg()方法仅执行一次?

Fix: Stop Repeated getImg() Calls for Image Src

Hey there! I see the issue—your getImg() method is getting called every time a screen event triggers a component re-render, which is totally unnecessary when you only need it once on initial load. Let's fix that.

Why This Happens

When you call a method directly in your template (like {{getImg()}}), Vue re-runs that method every time the component updates—this includes things like window resizes, scroll events, or even other data properties changing. Since your method is just checking a static iso value (I assume it doesn't change after initial load), we can avoid all those extra calls.

Solution: Calculate the Value Once on Initialization

Instead of calling the method in the template, compute the image suffix once when the component is created, store it in a data property, and then use that property in your img tag.

Step 1: Update Your Component Script

Add a data property to hold the suffix, then calculate it in the created hook (this runs once when the component is initialized):

export default {
  data() {
    return {
      imgSuffix: '' // We'll set this once on load
    };
  },
  created() {
    // Copy your getImg() logic here to run once
    this.imgSuffix = this.iso === '0' ? 'a' : 
                     this.iso === '1' ? 'b' : 
                     this.iso === '2' ? 'c' : 'd';
  },
  // You can remove the getImg() method now, since we don't need it in the template
  // getImg() { ... }
};

Step 2: Update Your Template

Replace the method call with the new data property:

<img src="./image/-ex-{{imgSuffix}}.png" />

Alternative: Use a Cached Computed Property (If iso Might Change)

If there's a chance iso could update later and you need the image to reflect that change, use a computed property instead. Computed properties are cached, so they only re-run when their dependencies (in this case, iso) change:

export default {
  computed: {
    imgSuffix() {
      return this.iso === '0' ? 'a' : 
             this.iso === '1' ? 'b' : 
             this.iso === '2' ? 'c' : 'd';
    }
  }
};

Then use it in the template the same way as above. This way, it only runs once initially, and again only if iso changes—no unnecessary calls on screen events.

Either approach will stop the repeated method calls and get you the one-time initial load behavior you want!

内容的提问来源于stack exchange,提问作者charles Lgn

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 09:53:14