【问题标题】:'Cannot read property 'color1' of undefined' error in vue.js'无法读取 vue.js 中未定义的属性'color1''错误
【发布时间】:2019-08-13 07:06:51
【问题描述】:

我正在用 storyblok、vue 和 nuxt 制作一个网站。在我的组件中,我试图通过从 storyblok API 中获取一个值并在我的对象中获取正确的 HEX 代码来更改组件的背景颜色。 但是,我似乎找不到问题所在,我收到了这个错误。

TypeError: Cannot read property 'color1' of undefined
at VueComponent.backgroundColor (app.js:6239)
at Watcher.get (commons.app.js:25459)
at Watcher.evaluate (commons.app.js:25564)
at VueComponent.computedGetter [as backgroundColor] (commons.app.js:25814)
at Object.get (commons.app.js:23107)
at Proxy.render (app.db592a6f79c830fedfca.hot-update.js:55)
at VueComponent.Vue._render (commons.app.js:24557)
at VueComponent.updateComponent (commons.app.js:25048)
at Watcher.get (commons.app.js:25459)
at Watcher.run (commons.app.js:25534)

如果有人能帮助我解决这个错误,我将不胜感激。 这是我的代码:

我正在尝试更改背景颜色的 div:

<div class="column image" :style="{ backgroundColor: backgroundColor}">
    <div class="image" :style="{ paddingTop: getRatio }">
        <img class="lazyload" :src="blok.image"/>
    </div>
</div>

我在 data() 函数中的对象:

methods: {

        data()
        {
            return {
                colors: {
                    color1: '#ffffff',
                    color2: '#5646F2',
                    color3: '#000000'
                }
            }
        }

    }

我的计算函数:

backgroundColor() {
    return !this.blok.color ? this.colors.color1 : this.colors[this.blok.color];
}

【问题讨论】:

  • 我不确定这是否会导致问题,但 data() 字段应该在 methods 之外,以便 vue 模板使用这些值
  • 您已经在 methods 对象中定义了 data
  • 可能你在backgroundColor函数中丢失了上下文this,在这种情况下你应该绑定函数或使用箭头函数。

标签: javascript vue.js nuxt.js storyblok


【解决方案1】:

this.colors 未定义,因为您的 data()methods 挂钩内。在methods 挂钩之外定义data 挂钩。

当您查找this.colors 时,它会查找在data 挂钩中定义的属性colors。当您寻找例如方法时。 this.myMethod(),它会根据需要在methodscomputed钩子中寻找方法。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-31
    • 2020-01-12
    • 2019-11-24
    • 2021-02-07
    • 2018-07-27
    • 2019-12-07
    • 1970-01-01
    相关资源
    最近更新 更多