Как обновить данные одного файлового компонента его методом? - PullRequest
0 голосов
/ 24 октября 2018

Я нахожусь в процессе изучения Vue.js, и теперь я изучаю Single File Component.Моя цель - запросить у пользователя их местоположение через API Geolocation, а затем обновить страницу, указав значения широты и долготы.Я могу получить значения координат через console.log, но не могу заставить SFC обновлять себя значениями.Возможно, я чего-то здесь упускаю.

geolocation.vue

<template>
  <p>Your location is: {{ text }}. Is this correct?</p>
</template>

<script>
  console.log('in geolocation.vue');
  let text = "N/A";

  export default {
    name: "geolocation",
    data: function () {
      return {
        text: text,
      }
    },
    methods: {
      findLocation: function() {
      let that = this;
      console.log('in findLocation()');
      if(navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(function (pos) {
          console.log('CONSOLE: ' + pos.coords.latitude + ', ' + pos.coords.longitude);
          that.text = pos.coords.latitude + ', ' + pos.coords.longitude;
        });
      }
    }
  }
}
</script>

<style scoped>
  p {
    color: red;
    font-size: 85%;
  }
</style>

App.vue

<template>
  <div class="center-text">
      <h1 class="site-title">{{ app_name }}</h1>
      <p>I'm the store page!</p>
      <p>Soon I'll display products according to the inventory at the distribution center(s) in the area.</p>
      <geolocation/>
  </div>
</template>

<script>
  import {mapGetters} from 'vuex';
  import geolocation from './geolocation';

  export default {
    computed: {
      ...mapGetters(['app_name'])
    },
    components: {
      geolocation
    },
    mounted: function() {
      geolocation.methods.findLocation();
    }
  };
</script>

<style scoped>
  .site-title {
      font-family: 'Lobster', cursive;
  }
  .center-text {
      text-align: center;
  }
</style>

1 Ответ

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

Добавьте это в geolocation.vue

mounted() {
  this.findLocation();
}

Удалите эти строки в App.vue

mounted: function() {
  geolocation.methods.findLocation();
}

Разделите ваш компонентво многие дочерние компоненты, и у него есть циклические зацепки.Когда компонент geolocation установлен, будет вызван findLocation и местоположение будет привязано к шаблону.

...