Подтвердить что ты не робот

Vue.js вызов AJAX внутри Модал

Я пытаюсь иметь модальное всплывающее окно с подробной информацией о кредитной карте. Подробности взяты из запроса AJAX. По какой-то причине экземпляр root Vue обновляется, но экземпляр компонента не является. Это то, что я сейчас имею -

HTML:

<!-- View Card Details Modal -->
<!-- Modal -->
<div class="modal fade" id="ccdetails" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
        <h4 class="modal-title" id="myModalLabel">View Card Details</h4>
      </div>
      <card-details cardid="{{$cc->card_id}}" :message="getCCDetails('{{$cc->card_id}}')"></card-details>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        <!-- <button type="button" class="btn btn-primary">Save changes</button> -->
      </div>
    </div>
  </div>
</div>

Vue JS:

<script type="text/javascript">
Vue.component('card-details', {
  template: '<div class="modal-body">@{{message}}</div>',
  // data is technically a function, so Vue won't
  // complain, but we return the same object
  // reference for each component instance
 props: ['message', 'cardid']
}),
new Vue({
  el: '#ccdetails',
  data: {
    cardid: '',
    message: ''
  },
  methods: {
        getCCDetails: function (id) {
            console.log(id)
            console.log('calling function')
             axios.get('/card/'.concat(id))
                  .then(function (response) {
                    this.message = JSON.stringify(response.data)
                  }.bind(this))
                  .catch(function (error) {
                    return this.message = 'Sorry there was an error'
                  }.bind(this));
        }
  }
})
</script>

Для вывода, экземпляр Root имеет cardid = undefined и message = the output, я хочу. У экземпляра cardDetails значение cardid правильное, но message = undefined.

4b9b3361

Ответ 1

Вы можете попробовать события

Добавить прослушиватель событий в компоненте:

Vue.component('card-details', {
        template: '<div class="modal-body">@{{message}}</div>',
        // data is technically a function, so Vue won't
        // complain, but we return the same object
        // reference for each component instance
        props: ['cardid'],

        data: {
            message: ''
        },

        mounted() {
            this.$parent.$on("card-details:message", message => {
                this.message = message;
            });
        },
    }),

добавить функцию испускания строки:

    getCCDetails: function (id) {
        console.log(id)
        console.log('calling function')
        axios.get('/card/'.concat(id))
            .then(function (response) {
                this.message = JSON.stringify(response.data)
                this.$emit('card-details:message', this.message) // <--
            }.bind(this))
            .catch(function (error) {
                return this.message = 'Sorry there was an error'
            }.bind(this));

    }

И сделайте вызов функции getCCDetails только на кнопке View Details , нажмите.

Ответ 2

Я звоню по телефону, попробуйте следующее:

  • Установите :message="message" в свои данные карты

  • то в корневом элементе Vue добавьте :cardid="{{$cc->card_id}}" и не забывайте cardid prop

  • затем реализуем метод mounted в корневом экземпляре и вызываем getCCDetails(this.cardid) оттуда.

  • внутри getCCDetails установить message свойство

Я надеюсь, что это поможет

Ответ 3

Модаль не для вызовов Ajax. Вы должны иметь Ajax-вызовы от контроллеров.