【问题标题】:VueJS prop is undefined when read in data() method在 data() 方法中读取时,VueJS 属性未定义
【发布时间】:2018-10-09 17:41:49
【问题描述】:

我无法理解 props 在 VueJS 中的工作原理,我们将不胜感激。这是一个简单的谷歌地图组件,我希望在页面上显示它并将 div 的 id 元素作为道具动态传递给底层模板。

html文件-

<div id="app">
    <google-map name="map"></google-map>
</div>

vue 文件-

<template>
    <div :id="mapName"></div>
</template>

<script>
module.exports = {
    name: 'google-map',
    props: [ 'name' ],
    data: () => {
        console.log(this.name); // ERROR: name is undefined
        return {
            mapName: this.name
        };
    },
    mounted: () => {
        const map = new google.maps.Map(document.getElementById(this.mapName), {
            zoom: 14,
            center: new google.maps.LatLng(39.305, -76.617)
        });
    }
}
</script>

<style scoped>
#map {
  width: 800px;
  height: 600px;
  margin: 0 auto;
  background: gray;
}
</style>

我得到的错误是 this.name 在组件对象的 data() 方法中未定义。

【问题讨论】:

  • 完全删除namedata;并使用name 而不是mapNameguide的介绍部分的解释。
  • 如果您希望发送name 并在子组件中使用mapName,请添加计算属性:computed: { mapName: () =&gt; this.name }

标签: javascript vue.js vuejs2 vue-component


【解决方案1】:

console.log(this.name); 返回 undefined 的原因是您正在使用箭头函数。应该是

data: function() {
    // ...
},

mounted: function() {
    // ...
}

data() {
    // ...
},

mounted() {
    // ...
}

说明:

https://vuejs.org/v2/guide/instance.html#Instance-Lifecycle-Hooks

【讨论】:

猜你喜欢
  • 2021-12-28
  • 2021-12-08
  • 2022-09-12
  • 2020-11-05
  • 2020-11-08
  • 2017-09-16
  • 2020-08-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多