Company logo
  • Jobs
  • Bootcamp
  • About Us
  • For professionals
    • Home
    • Jobs
    • Courses and challenges
    • Questions
    • Teachers
    • Bootcamp
  • For business
    • Home
    • Our process
    • Plans
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Calculator

0

126
Views
How to point to an external javascript file with an array in vue?

I have this example below, where I'm using dropdowns to filter through data. As you can see, I have the [items] hard-coded into javascript file. I'm hoping to point to an external javascript file, and hoping someone can help me with the best way to do that:

data: {
selectedType: '',
selectedCountry: '',
selectedYear: '',
items: [{
    name: 'Nolan',
    type: 'mercedes, ford',
    year: '2020',
    country: 'england'
  },
  {
    name: 'Edgar',
    type: 'bmw',
    year: '2020',
    country: 'belgium'
  },
  {
    name: 'John',
    type: 'bmw, audi',
    year: '2019',
    country: 'england'
  },
  {
    name: 'Axel',
    type: 'mercedes',
    year: '2020',
    country: 'england'
  }
],

},

https://jsfiddle.net/yrbs2650/1/

Thanks in advance!

7 months ago · Juan Pablo Isaza
1 answers
Answer question

0

The question is a bit unclear around 'external' javascript file, I'm assuming you meant it will still live in the source code but in a different file.

Use an import statement in your Vue file and an export statement in your js file

items.js

const items = [
  {
    name: 'Nolan',
    type: 'mercedes, ford',
    year: '2020',
    country: 'england'
  },
  {
    name: 'Edgar',
    type: 'bmw',
    year: '2020',
    country: 'belgium'
  },
  {
    name: 'John',
    type: 'bmw, audi',
    year: '2019',
    country: 'england'
  },
  {
    name: 'Axel',
    type: 'mercedes',
    year: '2020',
    country: 'england'
  }
];

export default items;

app.vue

import items from './items.js';

new Vue({
  el: '#app',
  data: {
    selectedType: '',
    selectedCountry: '',
    selectedYear: '',
    items: items,
  }
  ...

Depending on where you put your items.js file will change the import path, if it is a neighbor to your app.vue then ./items.js will do the trick.

The JSON format is preferred for storing data like this. Read about it here

7 months ago · Juan Pablo Isaza Report
Answer question
Find remote jobs