尝试在 Vue.js v-bind:src 中调用方法

Trying to Call a Method within Vue.js v-bind:src

我试图对 v-for 循环中的值执行“stripSemicolon”操作,但 Vue 抱怨我的字符串不再定义。以前是!

有什么想法吗??

我的代码是这样的...

        <ul id="userDropDown" v-if="users.length > 0 && selectedUserId == null">
            <li v-for="user in users" v-on:click="selectUser($event)">
                <span style="display:none;" v-bind:id="user.Id">{{user.Id}}</span>
                <img v-bind:src="stripSemi(user.ProfileImageURL)" width="75" height="75" style="border:1px solid black;border-radius:3px;"/>
                <span>{{user.UserName}}</span> &nbsp;|&nbsp;
                <span class="fullName">{{user.FullName}}</span>
            </li>
        </ul>
            stripSemi: function (s) {
                return s.substring(0, s.length - 1);
            }

它说 s is undefined

我正在从我的服务器返回值,其中填充了用户数组,并且单个特定用户的 ProfileImageURL 值等于 "/Assets/Images/Alex-Mom-Laura_dc044526-8a8b-49ae-bb37-0864830cb849.jpg;"

所以,我不确定为什么像这样 stripSemi(user.ProfileImageURL) 那样将值传递给 stripSemi 函数不起作用。

提前致谢。

考虑先处理从 API 返回的数组,然后再将其传递给 v-for

您可以使用 computed 函数执行此操作:

computed: {
  fixedUsers: function() {
    return this.users.map(user => {
      user.ProfileImageURL = this.stripSemi(user.ProfileImageURL);
      return user;
    }
  }
},
methods: {
  stripSemi: function(s) {
    if (typeof s === 'string') {
       return s.replace(';', '');
    } else {
       return s;
    }
  }
}

然后在你的组件中:

<ul id="userDropDown" v-if="users.length > 0 && selectedUserId == null">
    <li v-for="user in fixedUsers" v-on:click="selectUser($event)" :key="user.Id">
        <span style="display:none;" v-bind:id="user.Id">{{user.Id}}</span>
        <img v-bind:src="user.ProfileImageURL" width="75" height="75" style="border:1px solid black;border-radius:3px;"/>
        <span>{{user.UserName}}</span> &nbsp;|&nbsp;
        <span class="fullName">{{user.FullName}}</span>
    </li>
</ul>

Vue 抱怨我的字符串不再定义 - 请检查 ProfileImageURL 属性 是否存在于 users 数组对象中或没有。

我根据您的代码创建了一个片段,它工作正常。

new Vue({
  el: '#app',
  data: {
    users: [{
      id: 1,
      ProfileImageURL: 'abc.png;'
    }, {
      id: 2,
      ProfileImageURL: 'def.png;'
    }]
  },
  methods: {
    stripSemi: function (s) {
      return s.substring(0, s.length - 1);
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <ul id="userDropDown">
    <li v-for="user in users" :key="user.id">
      <img v-bind:src="stripSemi(user.ProfileImageURL)" width="75" height="75" style="border:1px solid black;border-radius:3px;"/>
    </li>
  </ul>
</div>