首页  >  问答  >  正文

在函数中访问 vue 可组合实例?

<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粉845862826P粉845862826416 天前556

全部回复(1)我来回复

  • P粉258788831

    P粉2587888312023-08-30 00:18:04

    如果你做得对,那么它就会起作用。

    但是您必须使用 functions() 而不是 lambda,因为 lambda 没有上下文,并且 this = window代码>

    const addProduct = function() {
        //this should be the instance of the cart composable?
        products.value.push({item: "Baseball Cap", quantity: 1, cart: this})
    }

    但我很难使用 .cart 属性中的 this 上下文。

    类似于cart.products.value[0].cart.products。它就是行不通。

    我建议您重新考虑设计。我不会那样做。

    检查操场。第二次是窗口。

    const { ref } = Vue;
    
    const useCart = function() {
        const products = ref([])
        const addProduct1 = function() {
            //this should be the instance of the cart composable?
            products.value.push({item: "Baseball Cap", quantity: 1, cart: this})
        }
        const addProduct2 = () => {
            //this should be the instance of the cart composable?
            products.value.push({item: "Baseball Cap", quantity: 1, cart: this})
        }
        return {
            products,
            addProduct1,
            addProduct2
        }
    }
    
    const cart = useCart();
    cart.addProduct1();
    console.log(cart.products.value[0].cart)
    cart.addProduct2();
    console.log(cart.products.value[1].cart)
    <script src="https://cdn.jsdelivr.net/npm/vue@3/dist/vue.global.prod.js"></script>

    回复
    0
  • 取消回复