首页 > 解决方案 > this.$getLocation 不是一个函数,这是 nuxt 告诉我的。我如何让它识别它为一个?

问题描述

<script>
export default {
        data() {
            return {
                map: null,
                myCoordinates: {
                    lat: 0,
                    lng: 0
                },
                zoom: 7
            }
        },
        created() {
            // does the user have a saved center? use it instead of the default
            if(process.browser) {
                this.myCoordinates = JSON.parse(localStorage.center);
            } else {
                // get user's coordinates from browser request
                this.$getLocation({})
                    .then(coordinates => {
                        this.myCoordinates = coordinates;
                    })
                    .catch(error => alert(error));
            }
            // does the user have a saved zoom? use it instead of the default
            if(localStorage.zoom) {
                this.zoom = parseInt(localStorage.zoom);
            }
        },
        mounted() {
            // add the map to a data object
            this.$refs.mapRef.$mapPromise.then(map => this.map = map);
        },
        methods: {
            handleDrag() {
                // get center and zoom level, store in localstorage
                let center = {
                    lat: this.map.getCenter().lat(),
                    lng: this.map.getCenter().lng()
                };
                let zoom = this.map.getZoom();
                localStorage.center = JSON.stringify(center);
                localStorage.zoom = zoom;
            }
        },
        computed: {
            mapCoordinates() {
                if(!this.map) {
                    return {
                        lat: 0,
                        lng: 0
                    };
                }
                return {
                    lat: this.map.getCenter().lat().toFixed(4),
                    lng: this.map.getCenter().lng().toFixed(4)
                }
            }
        }
    }

</script>

每次我运行 npm run dev 时,Nuxt 都会告诉我 this.$getLocation 不是一个函数。这段代码在 Vue-cli 中运行得非常好,但现在我无法让它在 Nuxt 中渲染地图,我切换到它以便于 MPA 使用。我如何让它认识到它是一个函数?我在代码中遗漏了一个错误吗?我从一个教程开始,只是稍微修改了一下,但是在另一个 Vue 项目中运行良好的代码现在不会转移到 Nuxt。

标签: vue.jsgeolocationnuxt.js

解决方案


推荐阅读