我正在尝试将从道具传递的项目添加到ref
使用vue-composition API
. 但是,我不知道为什么这些项目没有添加到数组中。也许我以错误的方式使用了扩展运算符,或者我的实现错误但未添加该项目。
vue-composition
方法位于不同的文件中,并在整个组件中使用。
我以这种方式将道具传递给产品组件:
<product
:id="12345667"
title="Pampers 9x Sensitive Baby Wet Wipes Filler, 576 Diaper Wipes"
price="14.59"
:rating="4"
image="https://images-na.ssl-images-amazon.com/images/I/41Yo4bc2uiL._AC_US160_.jpg"
>
</product>
同样,产品组件setup
如下:
<template>
<div class="product">
<button type="button" @click="addToCart(item)">Add to Basket</button>
</div>
</template>
<script>
import { useCart } from "../js/ShoppingCart";
export default {
setup(props) {
let item = props;
const { addToCart } = useCart();
return { item, addToCart };
},
props: {
id: Number,
title: String,
image: String,
price: String,
rating: Number,
}
};
</script>
ShoppingCart.js
我在哪里使用@vue-composition-api
import { ref } from "@vue/composition-api";
export function useCart() {
let basket = ref([]);
const addToCart = async (item) => {
// eslint-disable-next-line no-debugger
debugger;
return {
...basket,
item,
};
};
console.log(JSON.stringify(basket));
return { basket, addToCart };
}
我不知道我哪里做错了,basket
从不同的组件调用时数组总是空的。
更新的问题:
<template>
<div class="home">
<img
class="home__image"
src="https://images-na.ssl-images-amazon.com/images/G/01/AmazonExports/Fuji/2020/May/Hero/Fuji_TallHero_45M_es_US_2x._CB432534552_.jpg"
/>
<div class="home__row">
<product
:id="12345667"
title="Pampers 9x Sensitive Baby Wet Wipes Filler, 576 Diaper Wipes"
price="14.59"
:rating="4"
image="https://images-na.ssl-images-amazon.com/images/I/41Yo4bc2uiL._AC_US160_.jpg"
>
</product>
<product
:id="12345667"
title="Pampers 9x Sensitive Baby Wet Wipes Filler, 576 Diaper Wipes"
price="14.59"
:rating="4"
image="https://images-na.ssl-images-amazon.com/images/I/41Yo4bc2uiL._AC_US160_.jpg"
>
</product>
{{ basket }}
basket length {{ basket.value ? basket.value.length : 0 }}
</div>
</div>
</template>
<script>
// @ is an alias to /src
import Product from "@/components/Product.vue";
import { useCart } from "../js/ShoppingCart";
export default {
setup() {
const { basket } = useCart();
return { basket };
},
name: "Home",
components: {
Product,
},
};
</script>