【问题标题】:Vuejs TypeError: Cannot read property 'product' of undefinedVuejs TypeError:无法读取未定义的属性“产品”
【发布时间】:2020-11-23 21:35:19
【问题描述】:

我正在尝试使用这个product 数据:

data() {
    return {
        sitename: 'Vue.js Pet Depot',
        product: {
            id: 1001,
            title: 'Cat Food, 251lb bag',
            description: 'A 25 pound bag of <em>irresistible</em>,' +
            'organic goodness for your cat.',
            price: 2000,
            image: require('./assets/images/product-fullsize.jpg'),
        },
        cart: [],
    }
},

用这个方法:

methods: {
    addToCart: () => {
        console.log(this.product.title + ' was added to cart');
        // this.cart.push(this.product.id)
    }
}

这是我的模板:

<button class="default" v-on:click="addToCart">
    Add to cart
</button>

得到另一个Runtime Error

v-on 处理程序中的错误:“TypeError:无法读取属性 'product' 未定义”

【问题讨论】:

    标签: vue.js


    【解决方案1】:

    尝试使用以下代码一次

    methods: {
                addToCart: function() {
                    console.log(this.product.title + ' was added to cart');
                    // this.cart.push(this.product.id)
                }
            }
    

    【讨论】:

    • 使用箭头函数时,函数内部的this关键字指的是函数作用域。箭头函数中的 this 关键字不是指组件,您无法使用 this 关键字访问它们
    • @Sowmydhar 非常感谢!
    猜你喜欢
    • 2021-12-25
    • 1970-01-01
    • 2021-12-08
    • 2020-11-08
    • 2017-09-16
    • 2020-08-27
    • 2021-12-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多