2016-06-30 6 views
3

У меня проблема с запуском VueJS на мобильных устройствах. Я создал приложение прогнозирования погоды на copepen.ioVueJS не работает на мобильных устройствах

Вот ссылка на проект:

http://codepen.io/techcater/pen/xOZmgv

HTML код:

<div class="container-fluid text-center"> 
     <h1>Your Local Weather</h1> 
     <p> 
     {{location}} 
     </p> 
     <p> 
     {{temperature}} 
     <a @click="changeDegree">{{degree}}</a> 
     </p> 
     <p> 
     {{weather | capitalize}} 
     </p> 

     <img :src="iconURL" alt="" /> 
     <br> 
     <a href="https://ca.linkedin.com/in/dalenguyenblogger" target="_blank">by Dale Nguyen</a> 
<!-- <pre>{{$data | json}}</pre> --> 
    </div> 

JS код:

new Vue({ 
     el: '.container-fluid', 

     data: { 
      location: "", 
      temperature: "", 
      degree: "C", 
      weather: "", 
      iconURL: "" 
     }, 

     created: function(){ 
      this.getWeather(); 
     }, 

     methods: { 
      getWeather: function(){ 
      var that = this; 

      this.$http.get("http://ipinfo.io").then((response) => { 
        console.log(response.data); 
        that.location = response.data.city + ", " + response.data.country; 

        // Get weather informaiton 
        var api = 'ebd4d312f85a230d5dc1db91e20c2ace'; 
        var city = response.data.city; 
        var url = "http://api.openweathermap.org/data/2.5/weather?q={CITY}&APPID={APIKEY}&units=metric"; 
        url = url.replace("{CITY}",city); 
        url = url.replace("{APIKEY}", api); 

        that.$http.post(url,{dataType: 'jsonp'},{ 
       headers : { 
       'Content-Type' : 'application/x-www-form-urlencoded; charset=UTF-8' 
      }}).then((response) => { 
        console.log(response.data); 
        that.temperature = response.data.main.temp; 
        that.weather = response.data.weather[0]['description']; 
        that.iconURL = "http://openweathermap.org/img/w/" + response.data.weather[0]['icon'] + ".png"; 
        }, (response) => { 
         // error callback 
        }); 

       }, (response) => { 
        console.log(response.data);    
       });    
      }, 

      changeDegree: function() { 
      if(this.degree == "C"){ 
       this.degree = "F"; 
       this.temperature = Math.round((this.temperature*9/5 + 32)*100)/100; 
      }else { 
       this.degree = "C"; 
       this.temperature = Math.round(((this.temperature - 32)*5 /9)* 100)/100; 
      } 
      } 
     } 
     }) 

Он хорошо работает на моем ноутбуке, но не на мобильном телефоне. Сначала я подумал, что это из-за Кодепена. Это может вызвать что-то при запуске сайта. Однако, когда я создал проект на своем веб-сайте, он также не работает.

Помогите найти проблему? Спасибо,

+0

Что именно неудача в мобильном устройстве? –

+0

Какое мобильное устройство? Safari iOS, Android? – gurghet

+0

@YerkoPalma Я использую Iphone, и я пробовал сафари и браузер Chrome. –

ответ

0

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

Вот новый код:

getWeather: function(){ 
      var that = this; 

      this.$http.get('http://ipinfo.io', {'headers': { 
     'Origin': 'http://yourdomain.com'} 
      }).then(function(response) { 
        console.log(response.data); 
        that.location = response.data.city + ", " + response.data.country; 

        // Get weather informaiton 
        var api = 'ebd4d312f85a230d5dc1db91e20c2ace'; 
        var city = response.data.city; 
        var url = "https://crossorigin.me/http://api.openweathermap.org/data/2.5/weather?q={CITY}&APPID={APIKEY}&units=metric"; 
        url = url.replace("{CITY}",city); 
        url = url.replace("{APIKEY}", api); 

        that.$http.post(url,{dataType: 'jsonp'},{ 
       headers : { 
       'Content-Type' : 'application/x-www-form-urlencoded; charset=UTF-8' 
      }}).then(function(response) { 
        console.log(response.data); 
        that.temperature = response.data.main.temp; 
        that.weather = response.data.weather[0]['description']; 
        that.iconURL = "http://openweathermap.org/img/w/" + response.data.weather[0]['icon'] + ".png"; 
        }).then(function(){ 
         // error callback 
        }); 

       }).then(function(){ 
        console.log(response.data);    
       });    
      }, 
2

Ваш код, кажется, работает хорошо, за исключением того, что на codepen он дает мне ошибку XMLHttpRequest cannot load http://ipinfo.io/. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://s.codepen.io' is therefore not allowed access..

Вы можете поместить свое доменное имя на headers опций для включения перекрестного происхождения, вот пример:

this.$http.get('http://ipinfo.io', { 
    'headers': { 
     'Origin': 'http://yourdomain.com' 
    } 
}) 

Смотрите пример: http://bozue.com/weather.html

Я также заметил, что ты положил vue.min.js и vue-resource.js скриптов в неправильном порядке что может вызвать некоторую ошибку, vue.min.js должно быть на первом месте.

+0

если я использую crossorigin.me, он покажет ложное местоположение. Он работает на ваших мобильных устройствах? Спасибо –

+0

Обновлен ответ. Я еще не проверял его, но вы можете проверить http://bozue.com/weather.html на своих мобильных устройствах. – Rifki

+0

Спасибо за заголовки. Он отлично работает! О мобильном сайте. Я все еще не работаю :( –

Смежные вопросы