Nuxt: displaying local image from static folder - javascript

I'm getting started with nuxt. My static folder is in the screenshot. I've been trying to follow https://nuxtjs.org/guide/assets/#static
I've got a vuetify carousel component that was working fine with urls as the src. Now I want to try to serve local static files. I tried:
<template>
<v-carousel>
<v-carousel-item v-for="(item,i) in items" :key="i" :src="item.src"></v-carousel-item>
</v-carousel>
</template>
<script>
export default {
data () {
return {
items: [
{
src: '/static/52lv.PNG'
},
{
src: 'https://cdn.vuetifyjs.com/images/carousel/sky.jpg'
},
{
src: 'https://cdn.vuetifyjs.com/images/carousel/bird.jpg'
},
{
src: 'https://cdn.vuetifyjs.com/images/carousel/planet.jpg'
}
]
}
}
}
</script>
but now when I run the dev server I get a blank screen for that image of the carousel . The other images with urls work fine.
Inspecting the blank element in the browser, I see:
How can I display this image?

You don't need to specify the static folder, you should simply do:
src: '/52lv.PNG'

In addition to this question, if we would have it in '~assets/images/521v.PNG' ?
Instead of doing this
export default { data () {
return {
items: [
{
src: '/static/52lv.PNG'
},
Do this
src: `${require(`~assets/images/521v.PNG`)}`
and you would use it like this:
<img :src="items.src"/>

Related

VUE: How to make auto import all images from folder?

i trying auto import all images from folder. Under // tested is what i tried:
<template>
<p>classical art</p>
<img v-for="image in images" :key="image" :src="image.url" :alt="image.alt" />
</template>
<script>
export default {
data: function () {
return {
name: "classical-art",
images: [
{ url: require("../assets/images/classical-art/img-00001.jpg"), alt: "prvnĂ­" },
{ url: require("../assets/images/classical-art/img-00002.jpg"), alt: "druhĂ˝" },
],
};
},
};
// tested
const classicalArt = require(`../assets/images/classical-art/.jpg`)
classicalArt.forEach((image) => {
return image;
});
</script>
<style module lang="scss"></style>
Im not good in this things so i will need a help with this. Probably im just stupid, but i cant make it works. If possible, i want it async (lazy) or whatever it is.
----- UPDATE:
I tried something like that, but still nothing, but with require.context i should be able do this probably:
<template>
<p>classical art</p>
<img :src="getImgUrl()" v-bind:alt="req" />
</template>
<script>
export default {
data: function () {
return {
name: "classical-art",
};
},
methods: {
getImgUrl() {
var req = require.context(
"../assets/images/classical-art/",
false,
/\*.jpg$/
);
req.keys().forEach(function (key) {
req(key);
});
},
},
};
</script>
<style module lang="scss"></style>
I want when I add another image to the classical-art folder to create a new tag automatically and display the image without having to edit the code and manually register it
Can anyone help me with this?
For image rendering you must indicate the exact url to every image, so you have to type every url manually in the correct way.
BTW, your idea can be implemented with NodeJS. Node runtime has access to the file system, so url string can be created authomatically for every file.
Vue, unfortunately, has no real access to your files, it means every your component, file or image must be imported manually.

LwcWebpackPlugin with AliasModuleRecord for lwc.dev isn't loading HTML file for component

I use LwcWebpackPlugin to load Lightning Web Components. Everything works fine but because I want to load compoennts from 'lwc' direcotry the namescape won't work. I must get components from /lwc directory and I bypysed this with AliasModuleRecord (described here) where I import all components by name. Problem is that only JS file is loading. Browser don't throw any exception but HTML body is not rendered. I know that JS file works because console log from connectedCallback is showed in browser console. What I'm doing wrong?. Maybe I haven't imported some library? Here is fragment form my webpack.config.js:
new LwcWebpackPlugin({
modules: [
{ dir: 'src/modules' },
{ npm: 'lightning-base-components' },
...glob.sync(
`./{${sfdxProjectJSON.packageDirectories?.map(package => package.path).join(',')}}/main/default/lwc/**/*.js`,
{ ignore: ['./**/__tests__/**'] }
).map(path => {
const name = path.split('/').at(-2);
return {
"name": `c/${name}`,
"path": path.replace('./', '')
};
}, {})
]
})
and this all resoults with:
[{
name: 'ui/helloWorldExampleOne',
path: 'pb-base/main/default/lwc/helloWorld/__docs__/examples/helloWorldExampleOne/helloWorldExampleOne.js'
},
{
name: 'ui/helloWorld',
path: 'pb-base/main/default/lwc/helloWorld/helloWorld.js'
},
{
name: 'ui/exampleOne',
path: 'pb-commerce/main/default/lwc/exampleOne/exampleOne.js'
}]

I can't make a dynamic background image in vuejs, the url doesn't work

Im trying to make 6 blocks with different background images, i tried different options but none of them works,
This works:
<div :style="{ backgroundImage: `url(${require('../assets/images/img/img-1.jpg')})` }"></div>
These two doesnt work even if 'test' is literally the right path for the img:
<div :style="{ backgroundImage: `url(${require(test)})` }"></div>
<div class="col-4 jum-block" :style="{ backgroundImage: 'url(' + require(test) + ')' }"></div>
<script>
export default {
name: "Component",
data() {
return {
test: "../assets/images/img/img-1.jpg",
cardImgPath: "../assets/images/img/",
images: [
{ img: "img-1.jpg" },
{ img: "img-2.jpg" },
{ img: "img-3.jpg" },
{ img: "img-4.jpg" },
{ img: "img-5.jpg" },
{ img: "img-6.jpg" },
],
};
},
};
</script>
Given the usage of require(), I'm assuming your project is a Webpack-based project (scaffolded from Vue CLI).
The require() argument cannot be a fully dynamic expression for the same reason that import() calls cannot:
Dynamic expressions in import()
It is not possible to use a fully dynamic import statement, such as import(foo). Because foo could potentially be any path to any file in your system or project.
The import() must contain at least some information about where the module is located. Bundling can be limited to a specific directory or set of files so that when you are using a dynamic expression - every module that could potentially be requested on an import() call is included. For example, import(`./locale/${language}.json`) will cause every .json file in the ./locale directory to be bundled into the new chunk. At run time, when the variable language has been computed, any file like english.json or german.json will be available for consumption.
// imagine we had a method to get language from cookies or other storage
const language = detectVisitorLanguage();
import(`./locale/${language}.json`).then((module) => {
// do something with the translations
});
In your case, you could change your require() argument to include the image's path directory:
<div v-for="image in images"
:style="{ backgroundImage: `url(${require('../assets/images/img/' + image.img)})` }" ></div>
<script>
export default {
data() {
return {
images: [
{ img: "img-1.jpg" },
{ img: "img-2.jpg" },
{ img: "img-3.jpg" },
{ img: "img-4.jpg" },
{ img: "img-5.jpg" },
{ img: "img-6.jpg" },
],
};
},
};
</script>

V-For Image paths cannot find image. How can I add the correct file path when using v-for?

I am using vue/nuxt and I have an image carousel that I want to populate..
In my assets folder, I have a folder called "AreaPictures" that contains the images I would like to insert into the carousel.
my v-for looks like this:
<div class="area__slider">
<div v-swiper="swiperOption">
<div class="swiper-wrapper">
<div v-for="image in images" :key="image" class="swiper-slide">
<img :src="`../assets/AreaPictures${image.imageURL}`" alt="" />
</div>
</div>
</div>
</div>
Here is my script section:
<script>
export default {
name: 'Area',
data: function () {
return {
videoLanguage: 'English',
englishSrc: 'https://www.youtube.com/embed/lRKmJqDbVsY',
spanishSrc: 'https://www.youtube.com/embed/q0WkEkIMmQo',
currentSrc: 'https://www.youtube.com/embed/lRKmJqDbVsY',
swiperOption: {
grabCursor: true,
loop: true,
autoplay: {
delay: 5000,
disableOnInteraction: false,
},
pagination: {
el: '.swiper-pagination',
},
},
//----- ARRAY TO STORE THE IMAGE PATHS
images: [],
}
},
//-----IMPORT THE IMAGES ON MOUNT
mounted() {
this.importImages(require.context('~/assets/AreaPictures/', true))
},
methods: {
changeSrc() {
if (this.videoLanguage === 'English') {
this.currentSrc = this.englishSrc
} else {
this.currentSrc = this.spanishSrc
}
},
//-----THIS IS WHERE I IMPORT THE IMAGES
importImages(r) {
r.keys().forEach((key) => {
var path = key.substring(1) //-----THE PATH FOR SOME REASON CONTAINS A . SO I REMOVE IT
this.images.push({
imageURL: path, //----- CREATE A NEW OBJECT AND ADD IT TO IMAGES
})
})
},
},
}
</script>
As you can see I am getting the file names and then in the src of each image I am using:
:src="`../assets/AreaPictures${image.imageURL}`"
The error I'm getting in the console is:
vue.runtime.esm.js?2b0e:6785 GET http://localhost:3000/assets/AreaPictures/area1.jpg 404 (Not Found)
So it seems I am getting the correct file name however the path is not correct. I have also tried using #/assets/AreaPictures/area1.jpg
however this also doesn't work.
I'm guessing this is not the right way to reference file paths dynamically, can anybody explain how to do it in this case?
Thanks in advance!
Vue.js dynamic images not working
Check this, it helped me out a lot. You have to wrap your image sources in require() so Webpack can load it.

Adding pictures to Carousel from your own computer in Vuetify

I have a Carousel with some pics. I can use URL link to show the pics but when I want to show pics that are stored in my computer instead of the URL it doesn't show the pictures. What's the way to add a picture to your Carousel from your own computer?
Here is the Code:
<template>
<div class="caro">
<v-carousel >
<v-carousel-item
v-for="(item,i) in items"
:key="i"
:src="item.src"
>
<div class="text-xs-center">
</div>
</v-carousel-item>
</v-carousel>
</div>
</template>
<script>
export default {
data () {
return {
items: [
{
id: 'rack', src: 'https://logisticpackaging.com/CrXBdba4vG7B2k/wPHm6Sft56fw2V/wp-content/uploads/2015/06/pcb-racking-system5.jpg', title:'Rack Section'
},
{
id: 'subrack', src: '../assets/Parts.jpg' , title: 'Subrack Section'
},
{
id: 'parts', src: '../Hasan.jpg' , title: 'Parts Section'
},
{
id: 'admin', src: 'https://d15shllkswkct0.cloudfront.net/wp-content/blogs.dir/1/files/2013/04/Transactional-Database.jpg' , title: 'Database Section'
}
]
}
}
In my example the "rack" and "admin" section do have pictures since they get it from internet. But "parts" and "subrack" don't have pictures since I'm trying to use my own computer's pictures.
Are you running with npm in dev mode or Build? I have a folder called public, i put all my images / svg etc in folders in this public folder, because webpack will build this folder with the vue code.
So as source i use src="img/brand/logo.svg"
Except when you dont use webpack and a vue build template, i wouldnt recommend placing images elsewhere than in the public folder. This folder is easy to copy and most likely will be copied by webpack, so you can upload everything in the dist folder.
the two photos you are trying to render in the carousel are coming from two different sources, there is nothing wrong with the code, double check the photo source and confirm that the photo extension in the code matches the photo extension in the source folder
Although the Vue loader automatically converts relative paths to required functions, this is not the case with custom components. You can fix this problem by using require.
If you change the items array format, the problem will be fixed:
<script>
export default {
data () {
return {
items: [
{
id: 'subrack', src: require('../assets/Parts.jpg') , title: 'Subrack Section'
},
{
id: 'parts', src:require( '../Hasan.jpg'), title: 'Parts Section'
},
]
}
}

Categories

Resources