我想在我的 Vue 應用程式的組件中使用 Pinia 商店,但我不知道為什么必須在 {} 中回傳商店?return {foo}與return foo有什么區別?
import { usePiniaStore } from "../stores/mainStore";
export default {
setup() {
const piniaStore = usePiniaStore();
return { piniaStore }; // why isn't it 'return piniaStore' ?
},
};
uj5u.com熱心網友回復:
這實際上與 Pinia 無關,而是關于 Vue 期望作為setup()函式的回傳值。它需要一個物件。如果您嘗試回傳其他內容,Vue 會給您一個錯誤。
// this will give you an error "setup() should return an object. Received: number"
<script>
import { defineComponent } from 'vue'
export default defineComponent({
setup() {
let myVariable = 10
return myVariable
}
})
</script>
這樣做的原因是 Vue 需要迭代回傳物件的屬性(因此它知道值和名稱)并在組件實體上創建具有相同名稱的屬性(因此它們可以在模板中訪問)。這個很重要。
您的示例中的代碼:
return { piniaStore }
實際上是一樣的:
// creating new JS object
const returnObject = {
// first is property name
// second is property value (from existing variable)
piniaStore: piniaStore
}
return returnObject
...從 Vue 的角度來看,這是一個有效的代碼
要記住的重要一點是,只能從模板訪問回傳物件的屬性
// you can do this BUT only inner properties of the "myObject" will be accessible in the template
<script>
import { defineComponent } from 'vue'
export default defineComponent({
setup() {
let myObject = {
variableA: 10,
variableB: "some string"
}
return myObject
}
})
</script>
使用<div v-if="variableA">將起作用。使用<div v-if="myObject">不會。
Pinia 商店實際上是物件,因此直接從設定中回傳它們(而不將它們包裝在另一個物件中)可能是合法的并且會起作用。但以上所有內容仍然適用。您的模板只能訪問在該商店piniaStore中定義的屬性(狀態或 getter)和函式(操作)piniaStore
uj5u.com熱心網友回復:
這稱為物件解構。如果一個模塊回傳多個物件,即 {foo, goo, loo} 并且您只想選擇一個 foo。你可以使用return {foo}。但是如果模塊只回傳一個物件 foo,你可以使用return foo。 https://www.javascripttutorial.net/es6/javascript-object-destructuring/
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/457844.html
