如何使用其方法更新单个文件组件的数据?

时间:2018-10-24 13:57:53

标签: vue.js vuejs2 vue-component

我正在学习Vue.js,现在我正在学习单一文件组件。我的目标是通过Geolocation API询问用户的位置,然后使用其经纬度坐标值更新页面。我可以通过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 :(得分:2)

将此添加到 geolocation.vue

mounted() {
  this.findLocation();
}

App.vue

中删除这些行
mounted: function() {
  geolocation.methods.findLocation();
}

将您的组件拆分为许多子组件,并且它具有自身的循环钩子。 装入geolocation组件后,将调用findLocation并将位置绑定到模板中。