vue methods里的if 为什么不走if 执行结果是else

<template>
  <div>
    <div>我是user</div>
    <div class="user-list">
      <router-link style="padding: 0 20px" :to="'/user/'+item.tip+'/'+item.id" :key="index" v-for="(item, index) in userList">{{item.userName}}</router-link>
    </div>
    <div class="user-info" v-if="userInfo.userName">
      <p>姓名:{{userInfo.userName}}</p>
      <p>种族:{{userInfo.sex}}</p>
      <p>超能力:{{userInfo.hobby}}</p>
    </div>
  </div>
</template>

<script>
let data = [
  {
    id: 1,
    tip: 'common',
    userName: 'leo1',
    sex: '妖',
    hobby: '躲迷藏'
  },
  {
    id: 2,
    tip: 'vip',
    userName: 'leo2',
    sex: '魔',
    hobby: '毒霸'
  },
  {
    id: 3,
    tip: 'common',
    userName: 'leo3',
    sex: '人',
    hobby: '橡皮'
  },
  {
    id: 4,
    tip: 'vip',
    userName: 'leo4',
    sex: '神',
    hobby: '睡觉'
  }
]
export default {
  data () {
    return {
      userList: data,
      userInfo: {}
    }
  },
  watch: {
    $route () {
      this.getData()
    }
  },
  created () {
    this.getData()
  },
  methods: {
    getData () {
      let id = this.$route.params.userId
      console.log(id)
      if (id) {
        this.userInfo = this.userList.filter((item) => {
          return item.id === id
        })[0]
      } else {
        this.userInfo = {}
      }
    }
  }
}
</script>

<style>
</style>
阅读 5.3k
2 个回答
 return item.id === id * 1 // 类型错误,一个是字符串一个是数字,严格相等就报错了

你在getData 中主要是获取当前用户,但是你初始化的时候,userInfo 就是空,和 else 中的是一致的,不是这样吗?

data () {
    return {
      userList: data,
      userInfo: {}
    }
  }, 
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题