首頁  >  問答  >  主體

在函數中存取 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粉845862826417 天前557

全部回覆(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
  • 取消回覆