首页 > 解决方案 > Vue.js 属性或方法“addToCart”未在实例上定义

问题描述

我正在尝试制作一个组件,但它说我没有定义“addToCart”。我已经在同一个组件中定义了它,但我继续得到同样的错误?

Vue.component("solid-back",{
    template: `
    <div>
        <h1>{{ title }}</h1>
        <img :src="image">
        <h3>Price</h3>
        <p>{{price}}</p>
        <ul id="deets">
            <li v-for="detail in details">{{ detail }}</li>
        </ul>
            <button v-on:click="addToCart" 
                id="btn_add-to-cart">
                Add to Cart
            </button>
            <button id="btn_buy-now">
                Buy Now
            </button>
    </div>
    `,
    data() {
        return {
            title: "Solid Back Black Chair",
            image: "./photos/chairs/solidblack.jpg",
            price: "$34.00",
            details: ["3 feet tall", "Oakwood", "8 pounds"],
        }
    },
    method: {
        addToCart() {
            this.$emit("add-to-cart")
        }
    }
})

这是我继续收到的警告 [Vue warn]: Property or method "addToCart" is not defined on the instance but referenced during render. Make sure that this property is reactive, either in the data option or for class-based components, by initializing the property.

标签: vue.jserror-handling

解决方案


要在 Vue 中定义方法,属性键是methods. 看起来您的methods属性拼写错误(单数)method

将其更改为methods: { ... }应该可以工作:

    methods: {
        addToCart() {
            this.$emit("add-to-cart")
        }
    }

推荐阅读