Reputation: 68
How can I access global variables inside a vueJS component?
I’m trying to access the url
variable in the fetch function inside methods
but it won’t work.
var produits = [];
var url = '/dataset.json';
const vm = new Vue({
el: "#app",
data: {
produits: []
},
methods: {
handleKeyUp(event) {
console.log(event.key);
this.displayProducts()
},
displayProducts(produits) {
const htmlString = produits
.slice(0, 3)
.map((produit) => {
var replace = searchBar.value;
var re = new RegExp(replace, "gi");
return `
<li class="produitWrapper">
<div class="imgProduit">
<img src="https://d1tydw6090df56.cloudfront.net/products/320x240/${produit.imageKeyHashes}.jpg" alt="">
</div>
<div class="infosProduit">
<h2>${produit.title} - </h2>
<h3>${produit.mpn.replace(re, `<span class="highlight">$&</span>`)}</h3>
<br>
<p>${produit.description}</p>
</div>
</li>
`;
})
.join("");
productsList.innerHTML = htmlString;
},
fetch(url).then(res => res.json())
.then((output) => {
produits = output
})
.catch(err => { throw err });
}
})
Upvotes: 0
Views: 86
Reputation: 1201
There are multiple things going wrong in the code you pasted first things first:
the fetch function is kind of an invokation of another function that it looks like you ned to import first? anyway that invokation should be first of all inside his own function wrapper like this:
import fetch from '@/api/fetch'
let produits = [];
const url = '/dataset.json';
const vm = new Vue({
el: "#app",
data: {
produits: []
},
methods: {
handleKeyUp(event) {
console.log(event.key);
this.displayProducts()
},
displayProducts(products) {
const htmlString = products
.slice(0, 3)
.map((produit) => {
var replace = searchBar.value;
var re = new RegExp(replace, "gi");
return `
<li class="produitWrapper">
<div class="imgProduit">
<img src="https://d1tydw6090df56.cloudfront.net/products/320x240/${produit.imageKeyHashes}.jpg" alt="">
</div>
<div class="infosProduit">
<h2>${produit.title} - </h2>
<h3>${produit.mpn.replace(re, `<span class="highlight">$&</span>`)}</h3>
<br>
<p>${produit.description}</p>
</div>
</li>
`;
})
.join("");
productsList.innerHTML = htmlString;
},
fetch(url) {
fetch(url).then(res => res.json())
.then((output) => {
produits = output
})
.catch(err => { throw err });
}
}
})
Second i don't see where you want to invoke fetch by the way you try to handle the error it looks like you want that fetch of information done on the displayProducts function when you click somewhere in your template then the url should be a paramter passed there i am sure this is not the anwer your are looking for but you will need to provie a snippet of your issue to work with but i am sure i am pointing you in the right direction.
Upvotes: 1