Vue.js Свойство или метод «параметры» не определены в экземпляре, но на них ссылаются во время визуализации

#javascript #php #laravel #vue.js #inertiajs

#javascript #php #laravel #vue.js #inertiajs

Вопрос:

Я работаю с Vue.js (и Inertia.js ) и я хочу создать select в своей форме, но мой select после компиляции пуст, и консоль разработчика в веб-браузере выдает мне эту ошибку:

Свойство или метод «параметры» не определены в экземпляре, но на них ссылаются во время рендеринга. Убедитесь, что это свойство является реактивным либо в параметре data, либо для компонентов на основе классов, путем инициализации свойства

Пожалуйста, позвольте мне показать вам мой код для получения справки — Index.vue:

     <template>
    <app-layout>
        <div class="py-12">
            <div class="max-w-7xl mx-auto sm:px-6 lg:px-8">
                <div class="bg-white overflow-hidden shadow-xl sm:rounded-lg">
                    <div>
                      <div class="p-6 sm:px-20 bg-white border-b border-gray-200">
                        <div class="flex items-center justify-end mt-4">
                          <jet-application-logo class="block h-12 w-auto items-center mx-auto" />
                        </div>
                        <div>
                          <div class="max-w-7xl mx-auto py-10 sm:px-6 lg:px-8">
                            <jet-form-section @submitted="createInvestment">
                            
                            <template #title>
                              Investment gateway
                            </template>

                            <template #form>
                              <div class="mx-auto text-center">
                                <jet-input-amount id="amount" type="number" name="amount" placeholder="Amount for invest" v-model="investmentForm.amount" />
                                <jet-input-error :message="investmentForm.error('amount')" class="mt-2" />
                                <select v-model="currency" name="currency" class="input-currency">
                                  <option v-for="option in options" v-bind:value="option.value">
                                     {{ option.text }}
                                  </option>
                                </select>
                              </div>
                              <div class="mx-auto text-center">
                                <jet-input id="card_number" type="email" name="card_number" placeholder="Card Number" v-model="investmentForm.paypal" />
                                <jet-input-error :message="investmentForm.error('card_number')" class="mt-2" />
                              </div>
                              <div class="mx-auto text-center nomad-slash">
                                <jet-input-card id="card_expiration_month" type="email" name="card_expiration_month" placeholder="MM" v-model="investmentForm.paypal" />
                                <jet-input-error :message="investmentForm.error('card_expiration_month')" class="mt-2" />
                                /
                                <jet-input-card id="card_expiration_year" type="email" name="card_expiration_year" placeholder="YY" v-model="investmentForm.paypal" />
                                <jet-input-error :message="investmentForm.error('card_expiration_year')" class="mt-2" />
                                <jet-input-card id="card_cvv" type="email" name="card_cvv" placeholder="CVV" v-model="investmentForm.paypal" />
                                <jet-input-error :message="investmentForm.error('card_cvv')" class="mt-2" />
                              </div>

                            </template>
                            <template #actions>
                                <jet-action-message :on="investmentForm.recentlySuccessful" class="mr-3">
                                  Your money are on the way!
                                </jet-action-message>

                                <jet-button :class="{ 'opacity-25': investmentForm.processing }" :disabled="investmentForm.processing">
                                  Invest
                                </jet-button> 
                                <br /><br /> 
                            </template>
                          </jet-form-section>
                          </div>
                        </div>
                        
                </div>
              </div>
            </div>
          </div>
        </div>

    </app-layout>
</template>

<script>

    import JetActionMessage from './../../Jetstream/ActionMessage'
    import JetFormSection from './../../Jetstream/FormSection'
    import JetButton from './../../Jetstream/Button'
    import JetInput from './../../Jetstream/Input'
    import JetInputAmount from './../../Jetstream/InputAmount'
    import JetInputCard from './../../Jetstream/InputCard'
    import JetLabel from './../../Jetstream/Label'
    import JetInputError from './../../Jetstream/InputError'
    import JetApplicationLogo from './../../Jetstream/ApplicationLogo'
    import AppLayout from "./../../Layouts/AppLayout";

    export default {
        name: "Index",
        components: {AppLayout, JetInput, JetLabel, JetFormSection, JetButton, JetActionMessage, JetInputError, JetApplicationLogo, JetInputAmount, JetInputCard},
        data() {
            return {
                investmentForm: this.$inertia.form({
                    amount: '',
                    currency: '',
                    options: [
                      { text: 'amp;#36; USD', value: 'usd' },
                      { text: 'R ZAR', value: 'zar' },
                      { text: 'amp;#8364; EUR', value: 'eur' },
                      { text: 'amp;#163; GBP', value: 'gbp' },
                      { text: 'amp;#8377; INR', value: 'inr' },
                      { text: 'amp;#36; AUD', value: 'aud' },
                    ],
                    card_number: '',
                    card_expiration_month: '',
                    card_expiration_year: '',
                    card_cvv: '',
                }, {
                    bag: 'createInvestment',
                    resetOnSuccess: false,
                }),
            }
        },
        methods: {
            createInvestment() {
                this.investmentForm.post('/input/create', {
                    preserveScroll: true,
                });
            }
        }
    }
</script>

<style scoped>

</style>
  

Ответ №1:

В вашем v-for цикле VueJS пытается найти options ключ в вашем объекте данных. Ваши параметры находятся под investmentForm ключом, поэтому в вашем v-for вместо

 v-for="option in options"
  

Вы должны написать

 v-for="option in investmentForm.options"
  

Ошибка, которую вы получаете, просто означает, что Vue не знает, что options такое, поскольку он нигде не может его найти.

Ответ №2:

options находится внутри investmentForm данных, поэтому вам необходимо обновить это

   <option v-for="option in investmentForm.options" v-bind:value="option.value">
      {{ option.text }}
 </option>
  

Ответ №3:

options находится внутри investmentForm, поэтому его необходимо вызывать в шаблоне, подобном this investmentForm.options .

Альтернативой уже приведенным решениям было бы добавить вычисляемый метод, таким образом, вам не нужно менять шаблон:

 // ...

computed: {
    options() {
        return investmentForm.options;
    }
},

// ...