Как загрузить внешние данные Json в vue.js - PullRequest
0 голосов
/ 17 октября 2019

Я написал компонент, показывающий некоторые изображения, и когда вы щелкаете по нему, модальное всплывающее окно показывает дополнительную информацию.

Данные, отображаемые в диалоговом окне, имеют формат json, встроенный в компонент, теперь я хочу, чтобы данные извлекалисьпо какой-то внешней ссылке.

Здесь вы можете увидеть пример файла данных Json и здесь Codepen

// global component
Vue.component("my-car", {
  template: "#car-info",
  props: {
    active: "active",
    isActive: "isActive",
    carlist: "carlist",
    show: {
      type: Boolean,
      required: true,
      twoWay: true
    }
  },

  methods: {
    // check wich content index is active
    modalActiveContent: function(i) {
       return this.active === i
    },
    // close modal
    setModalClose: function() {
     this.show = false;
      //if need set active content to zero object       
     // this.active = 0;
    }
  }
});
new Vue({
  el: "#app",
  data: {
    active: 0,
    showModal: false,
    cars: [
    {
      img: "https://image.tmdb.org/t/p/w154/qN73wDiyplutRKOHiXaLYFgPhwK.jpg",
      title: "Default",
      description: "lorem lorem lorem."
    },{
       img: "https://image.tmdb.org/t/p/w154/tWBo7aZk3I1dLxmMj7ZJcN8uke5.jpg",
      title: "Citroen",
      description: "Lorem ipsum."
    }, {
       img: "https://image.tmdb.org/t/p/w154/qN73wDiyplutRKOHiXaLYFgPhwK.jpg",
      title: "Honda",
      description: "Lorem ipsum lorem lorem."
    }
]
  }, 
  methods: {
    // set active modal and set index wich content is activeted
    modalOpen: function(i) {
        this.showModal = true; 
        return this.active = i;
      }
  }
});
.modal-mask {
  position: fixed;
  z-index: 9998;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, .5);
  display: table;
  transition: opacity .3s ease;
}

.modal-wrapper {
  display: table-cell;
  vertical-align: middle;
}

.modal-container {
  width: 300px;
  margin: 0px auto;
  padding: 20px 30px;
  background-color: #fff;
  border-radius: 2px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, .33);
  transition: all .3s ease;
  font-family: Helvetica, Arial, sans-serif;
}

.modal-header h3 {
  margin-top: 0;
  color: #42b983;
}

.modal-body {
  margin: 20px 0;
}

.modal-default-button {
  float: right;
}

/*
 * the following styles are auto-applied to elements with
 * v-transition="modal" when their visiblity is toggled
 * by Vue.js.
 *
 * You can easily play with the modal transition by editing
 * these styles.
 */

.modal-enter, .modal-leave {
  opacity: 0;
}

.modal-enter .modal-container,
.modal-leave .modal-container {
  -webkit-transform: scale(1.1);
  transform: scale(1.1);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/1.0.17/vue.js"></script>
<div id="app">
 <img src="{{car.img}}" alt="{{car.title}}" class="demo-img" v-for="car in cars" id="show-modal" @click="modalOpen($index)">
      
    
 
  <my-car :show.sync="showModal" :carlist="cars" :active.sync="active"></my-car>
<!-- Var dump data -->
</div>
 
<template id="car-info">
  <div  class="modal-mask" v-show="show" transition="modal" aria-hidden="true" role="dialog" aria-labelledby="modalTitle" aria-describedBy="modalDescription" style="border: 2px solid black;">
    <div class="modal-container">
    <h4>Detailed View1</h4>
  <div class="car-item" v-for="car in carlist" v-if="modalActiveContent($index)">
    <img src="{{car.img}}" alt="{{car.title}}">
      <h1>{{car.title}}</h1>
      <p>{{car.description}}</p>
     <button v-if="modalActiveContent($index)" class="modal-default-button"
              @click="setModalClose">
              Close me please
            </button>
  </div>
      </div>
  </div>
</template>

Ответы [ 3 ]

0 голосов
/ 17 октября 2019

Замените ваш код Vue следующим образом. (и, конечно, не забудьте npm i axios --save или эквивалент пряжи.

import axios from 'axios'

new Vue({
  el: "#app",
  data: {
    active: 0,
    showModal: false,
    cars: []
  }, 
  methods: {
    // set active modal and set index wich content is activeted
    modalOpen: function(i) {
        this.showModal = true; 
        return this.active = i;
      }
  },
  created(): {
    axios.get('http://http://ideazfactory.in/library/jj.json')
      .then(response => {
         this.cars = response;
      }
  }
});

Обратите внимание, что существует некоторая проблема с возвращением JSON из предоставленного вами URL-адреса. Это дает мне недопустимую ошибку JSON на моемБраузер. Создан хук жизненного цикла, который вызывается при инициализации экземпляра Vue. Здесь можно запустить функции для извлечения данных, он вызывается до визуализации представления.

0 голосов
/ 17 октября 2019

Добавьте функцию mounted для загрузки внешних данных JSON, как показано ниже.

mounted: function () {
  this.$nextTick(function () {
    // Code that will run only after the
    // entire view has been rendered
    // Make a request for a user with a given ID
    axios.get('http://ideazfactory.in/library/jj.json')
        .then(function (response) {
        // handle success
        console.log(response);
        this.cars = response.data;
    })
    .catch(function (error) {
        // handle error
        console.log(error);
    });
  })
}
0 голосов
/ 17 октября 2019
  1. Данные, предоставленные с вашим файлом, не в формате JSON

Синтаксис JSON

Синтаксис JSON с W3Schools

Если вы хотите получить данные из внешней ссылки, используйте axios

npm - axios

cdn - axios

axios.get('/path-to-json-dataset')
  .then(function (response) {
    console.log(response);
  })

ПРИМЕР

axios.get('http://ideazfactory.in/library/jj.json')
  .then(function (response) {
    this.cars = response.data;
  })
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...