Доступ к значениям реквизита внутри локального компонента vuejs - PullRequest
0 голосов
/ 26 октября 2018

У меня есть Vue Экземпляр с двумя локальными компонентами, оба компонента имеют props из данных Vue Instance.Но когда я пытаюсь получить доступ к props значениям от одного из локальных компонентов, значения не определены.

Это код

var custom_erp_widget = new Vue({
    el : '#custom-erp-widgets',
    data : {
        showContainerHeader : false,
        currentModuleName : 'foo',
        currentModuleFormID : '5',
        currentModuleReportID : '6'
    },
    components : {
        'custom-erp-header' : {
            template : '<div class="col-12" id="custom-erp-widget-header">'+
                        '{{ currentModuleName.toUpperCase() }}'+
                       '</div>',
            props : ['currentModuleName']
        },
        'custom-erp-body' : {
            template : '<div class="col-12" id="custom-erp-widget-body">'+
                       '</div>',
            props : ['currentModuleFormID','currentModuleReportID'],
            // for emitting events so that the child components
            // like (header/body) can catch and act accordingly
            created() {
                var _this = this;
                eventHub.$on('getFormData', function(e) {
                    if(e == 'report'){
                        console.log(_this.$props);

                        _this.getReportData();
                    }
                    else if(e == 'form'){
                        console.log(_this.$props);
                        _this.getFormData();
                    }

                });

              },

            methods : {
                // function to get the form data from the server
                // for the requested form
                getFormData : function(){
                    var _this = this;
                    //here the logs are returinig undefined
                    //but it is having values in the data from the root Instance
                    console.log(_this.$props.currentModuleFormID);
                    console.log(_this.currentModuleFormID);

                    axios
                        .get('http://localhost:3000/getFormData',{
                            params: {
                                formID: _this.currentModuleFormID + 'a'
                            }
                        })
                        .then(function(response){

                            console.log(response);

                        })
                }

            }

        }
    },

})

Это использование HTML компонента

<div class="row" id="custom-erp-widgets" v-show="showContainerHeader">

    <custom-erp-header :current-module-name='currentModuleName'></custom-erp-header>    
    <custom-erp-body></custom-erp-body>

</div>

Как получить доступ к значениям реквизита в функции локального компонента?

Ouptput

Ответы [ 2 ]

0 голосов
/ 26 октября 2018

Вы должны передать реквизиты компоненту custom-erp-body:

<custom-erp-body 
  :currentModuleFormID="currentModuleFormID" 
  :currentModuleReportID ="currentModuleReportID">
</custom-erp-body>
0 голосов
/ 26 октября 2018

Кажется, что проблема в ваших именах реквизитов , потому что Vue ожидает, что имена ваших реквизитов в шаблонах DOM будут заключены в кебаб.

Имена атрибутов HTML не чувствительны к региструпоэтому браузеры будут интерпретировать любые заглавные буквы как строчные.Это означает, что когда вы используете встроенные шаблоны DOM, имена верблюдов CamelCased должны использовать их эквиваленты в кебабе (с разделителями-дефисами).

Так что для currentModuleFormID ожидается current-module-form-i-d вШаблон DOM, а не current-module-form-id, как вы ожидаете.Попробуйте изменить currentModuleFormID на currentModuleFormId с нижним регистром d в конце и использовать current-module-form-id в шаблоне, и я предполагаю, что это должно работать.

var custom_erp_widget = new Vue({
    el : '#custom-erp-widgets',
    data : {
        showContainerHeader : false,
        currentModuleName : 'foo',
        currentModuleFormId : '5',
        currentModuleReportId : '6'
    },
  ....

<custom-erp-body 
  :current-module-form-id="currentModuleFormId" 
  :current-module-report-id ="currentModuleReportId">
</custom-erp-body>
...