在函数中访问 vue 可组合实例?
P粉845862826
P粉845862826 2023-08-29 08:59:18
0
1
416
<p>假设我有一个简单的 vue 可组合函数,我想在我的应用程序中多次重复使用它。在本例中,它有一个响应式属性(产品、一个包含产品列表的数组)和一个方法“addProduct”,该方法将新元素推送到数组。</p> <pre class="brush:php;toolbar:false;">export function useCart(){ const products = ref([]) const addProduct() =>{ products.push({item: "Baseball Cap", quantity: 1}) } return { products, addProduct } }</pre> <p>效果很好。但是,我想将可组合购物车的实例传递给每一行,以便该行可以通过属性“cart”访问父“购物车”。</p> <p>我希望以下内容能够发挥作用。我相信“this”应该引用调用该函数的对象(购物车实例):</p> <pre class="brush:php;toolbar:false;">export function useCart(){ const products = ref([]) const addProduct() =>{ //this should be the instance of the cart composable? products.push({item: "Baseball Cap", quantity: 1, cart: this}) } return { products, addProduct } }</pre> <p>但是,当我在使用可组合项的组件中进行测试时,“this”的值未定义:</p> <pre class="brush:php;toolbar:false;">const testCart = useCart testCart.addProduct()</pre> <p>为什么在此上下文中未定义“this”,以及如何访问可组合方法内部的可组合实例?</p>
P粉845862826
P粉845862826

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!