Vue - пропуск массива prop через компонент vue приводит к неопознанной ошибке - PullRequest
1 голос
/ 10 октября 2019

Я пытаюсь передать массив дат моему компоненту, но он продолжает выдавать

[Vue warn]: Property or method "dates" is not defined on the instance
   but referenced during render

Я не понимаю, почему, так как я получаю переменную в подпорках, я 'м, используя Laravel, кстати. Я могу использовать подобные реквизиты, если я ссылаюсь на них в экземпляре vue в моем файле app.js, но я не могу получить переменные php в этот файл, так что нет никакого смысла.

Base:

HTML:

 <div class="graph">
            <linegraph :dates="dates"></linegraph>
        </div>

JS:

var dates = {
        monday: '{{ $monday }}',
        tuesday: '{{ $tuesday }}',
        wednsday: '{{ $wednsday }}',
        thursday: '{{ $thursday }}',
        friday: '{{ $friday }}',
        saturday: '{{ $saturday }}',
        sunday: '{{ $sunday }}'
    }

Компонент:

Шаблон:

    <div class="chart_card">
        <h2>{{ dates }}</h2>
        <div>
            <GChart
                :settings="{ packages: ['corechart'] }"
                type="LineChart"
                :data="chartData"
                :options="chartOptions"
            />
        </div>
    </div>

JS:

   export default {
    name: 'linegraph',
    props: ['dates'],
    data() {
      return {

        } 
    },
    components: {
        GChart
    },
    methods: {

    },
  };

Запуск экземпляра Vue:

/**
 * First we will load all of this project's JavaScript dependencies which
 * includes Vue and other libraries. It is a great starting point when
 * building robust, powerful web applications using Vue and Laravel.
 */

require('./bootstrap');



window.Vue = require('vue');

import Vue from 'vue';

import InstantSearch from 'vue-instantsearch';

Vue.use(InstantSearch);

/**
 * The following block of code may be used to automatically register your
 * Vue components. It will recursively scan this directory for the Vue
 * components and automatically register them with their "basename".
 *
 * Eg. ./components/ExampleComponent.vue -> <example-component></example-component>
 */

// const files = require.context('./', true, /\.vue$/i);
// files.keys().map(key => Vue.component(key.split('/').pop().split('.')[0], files(key).default));


// DASHBOARD
Vue.component('linegraph', require('./components/dashboard/line_graph.vue').default);

/**
 * Next, we will create a fresh Vue application instance and attach it to
 * the page. Then, you may begin adding components to this application
 * or customize the JavaScript scaffolding to fit your unique needs.
 */

const app = new Vue({
    el: '#app',
    data: {

    },
});

Любая помощь будет потрясающей! Спасибо :) 1033 *

Ответы [ 3 ]

1 голос
/ 10 октября 2019

Вам необходимо определить переменные внутри метода данных, чтобы сделать его доступным в HTML-части компонента vue.

Если данные поступают из некоторого бэкэнда, такого как PHP, вы можете создать переменную в данных и назначить ейзначение из бэкэнда.

data () {
  return {
    dates: []
  }
},

и в смонтированном или любом другом крючке, который вы используете для доступа к данным

methods: {
  fetchData (datesFromBK) {
    this.dates = datesFromBK
  }
}
1 голос
/ 10 октября 2019

Попробуйте: вместо того, чтобы создавать переменную для ваших дат, перейдите к месту, где вы делаете это:

<div class="graph">
    <linegraph :dates="dates"></linegraph>
</div>

И замените :dates="dates" на это:

:dates="{{ json_encode([
    'monday' => $monday,
    'tuesday' => $tuesday,
    'wednesday' => $wednesday,
    'thursday' => $thursday,
    'friday' => $friday,
    'saturday' => $saturday,
    'sunday' => $sunday
]) }}"
0 голосов
/ 10 октября 2019

Попробуйте поместить серверную часть JS (с переменными из PHP) перед инициализацией экземпляра Vue на chart_card.

ИЛИ

Шаблон:

<div v-if="dates" class="chart_card">
    <h2>{{ dates }}</h2>
</div>

(Надеюсь, этот h2 только для отладки, поскольку он не будет отображать список дат, просто мусор;))

...