简体   繁体   中英

How do I go about integrating a regular javascript file into my vue.js page?

I have a js script written in pretty much the same syntax as one would write one without vue.js, although I haven't included semicolons (not sure how this might help but throwing it in there anyway).

I'm curious as to whether I should put this script into the format of one object with multiple methods and data/variables as properties of that object, similar to how it is written at the bottom of a vue.js page.

I'm entirely new to vue, but not to JavaScript.

If I have some script called myscript.js , and I want to include this file, its functions and variables, in a .vue file (not in the main.js file, because I don't want it to be loaded on every page, just the one I'm working with), how exactly should I go about including it in the file?

I am extremely aware as to how vague this is, and I'm absolutely happy to elaborate, but at the moment my mind is unable to intuitively explain exactly what I mean (mostly out of exhaustion unrelated to programming).

Any advice would be greatly appreciated.

Thanks!

JS code can be imported in the JS part of .vue files exactly as you'd import regular JS files. You don't need to import Vue components, it can be anything you can import normally - data, functions, objects, etc. Minimal example:

// name.js
export default 'John Doe';

// Hello.vue
<template>
  <p>Hello, my name is {{fullName}}!</p>
</template>
<script>
import name from './name';
export default {
  data() { return {
    fullName: name,
  }}
}
</script>

You can just use in .vue file require('./myscript.js') and use strict directive by adding use strict; to the beginning the script

EDIT : you have to export your functions in myscript.js file

// myscript.js
export function fn1() {...} 
export function fn2() {...}

and then import them in your vue file

import * as MyFn from './myscript.js'

MyFn.fn1();
MyFn.fn2();

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