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

Vue组件挂载时按传入props获取数据,showLatest始终为undefined怎么办

问题原因
  • prop命名格式不匹配:Vue2中HTML模板的属性不支持驼峰命名,所有camelCase格式的prop在父组件模板中传递时必须转换为kebab-case格式。你在父组件中使用:showLatest="true"传值,Vue无法将其映射到组件声明的showLatest prop上,所以读取时为undefined。
  • 方法配置项拼写错误:Vue组件的方法声明配置项是methods(复数形式),你代码中写成了单数形式的method,导致fetch方法没有被挂载到组件实例上,后续调用会抛出未定义错误。
修复方案

1. 修改父组件HTML传值格式

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  {{ message }}
  <!-- 驼峰prop改为kebab-case格式传递 -->
  <book :show-latest="true"></book>
</div>

2. 修改组件配置项拼写

Vue.component('book', {
    props: ["showLatest"],
  data: function() {
    return {
        books: null
    }
  },
  template: '<ul><li v-for="book in books">This is a book {{ book.name }} <small><i>{{ book.publisher}}</i></small></li></ul>',
  // 单数method改为复数methods
  methods: {
    fetch: function() {
        this.books = [
        {
          name: "Latest 1",
          publisher: "publisher_test1"
        },
        {
          name: "Latest 2",
          publisher: "publisher_test2"
        },
        {
          name: "Latest 3",
          publisher: "publisher_test3"
        }
      ];
    }
  },
  mounted: function() {
    console.log(this.showLatest);
    if(!this.showLatest) {
            this.books = [
        {
          name: "Test 1",
          publisher: "publisher_test1"
        },
        {
          name: "Test 2",
          publisher: "publisher_test2"
        },
        {
          name: "Test 3",
          publisher: "publisher_test3"
        }
      ];
    } else {
        this.fetch();
    }
  }
})

var app = new Vue({
  el: '#app',
  data: {
    message: 'Digital Library!'
  }
})

如果需要支持后续showLatest值动态变更触发数据重新加载,可以额外添加watch配置监听showLatest的变化,变更时重新执行数据加载逻辑即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 01:39:03