简体   繁体   中英

Define Vue methods functions in different js page

Newbie, sorry in advance for the stupid question

I have a vue component vuu

/path_to_main/vue_file/app.js

const vuu = new Vue({
    el: '#vuu',
    data: {
        latitude: 'longi',
        longitude: 'lati'
    },
    created: function(){this.checkIfGeolocationAvailable();},
    methods: {
        checkIfGeolocationAvailable: function(){
            getLocation(); // <-- this function
        }


    }
});

Now I want to define getLocation() on a different js page say

/path_to_main/vue_file/helper.js

function getLocation() {alert("Hello");}

How can I do this? or is this a totally wrong approach?

Being modular is never the wrong approach.

Use es6 modules and a transpiler such as webpack , typescript , etc.

helper.js

export function getLocation() {alert("Hello");}

main.js

import {getLocation} from './helper.js'

Once you start using a transpiler, you should also consider using Vue single file components . Furthermore, by leveraging vue-cli-3 , you can eliminate much of the heavy boilerplate for the transpiler configuration, testing, and building.

I created a helper folder, but it was not necessary

helper/getLocation.js

export default function getLocation() {
  alert("Hello")
}

App.vue

<template>
  <div id="app">
  </div>
</template>

<script>
import getLocation from './helper/getLocation.js'

export default {
  name: 'App',
  data() {
    return {}
  },
  mounted() {
    getLocation()
  }
}
</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM