在函数中访问 vue 可组合实例?
P粉845862826
P粉845862826 2023-08-29 08:59:18
0
1
433
<p>假设我有一个简单的 vue 可组合函数,我想在我的应用程序中多次重复使用它。在本例中,它有一个响应式属性(产品、一个包含产品列表的数组)和一个方法“addProduct”,该方法将新元素推送到数组。</p> <pre class="brush:php;toolbar:false;">export function useCart(){ const products = ref([]) const addProduct() =&gt;{ products.push({item: &quot;Baseball Cap&quot;, 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() =&gt;{ //this should be the instance of the cart composable? products.push({item: &quot;Baseball Cap&quot;, 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

Beliebte Tutorials
Mehr>
Neueste Downloads
Mehr>
Web-Effekte
Quellcode der Website
Website-Materialien
Frontend-Vorlage
Über uns Haftungsausschluss Sitemap
Chinesische PHP-Website:Online-PHP-Schulung für das Gemeinwohl,Helfen Sie PHP-Lernenden, sich schnell weiterzuentwickeln!