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!
CodePudding user response:
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