i want import image file from specific link into my vue variable can someone help me
i tried with required but it doesn't work this.imagefile = require(linkofimage)
does anyone know how to solve it
I suggest you to import first the images as constants and assign them to your vue data properties in hooks or methods:
<template>
<div>
<img :src="imageDirect" alt="alert">
<img :src="imageOnHook" alt="alert">
<img :src="imageOnMethod" alt="alert">
<img :src="imageRequire" alt="alert">
</div>
</template>
<script>
const image = require('#/assets/alert_logo_card.png')
export default {
data: () => ({
imageDirect: image,
imageOnHook: null,
imageOnMethod: null,
imageRequire: null,
}),
mounted() {
this.imageOnHook = image
this.imageRequire = require('#/assets/alert_logo_card.png')
this.assignImage()
},
methods: {
assignImage() {
this.imageOnMethod = this.imageDirect
}
}
}
</script>
I'm using the same image just for example purpose.
Something like this also will work:
methods: {
assignImage() {
this.imageOnMethod = this.imageDirect
}
}
Showing an image from the network:
<template>
<div>
<img :src="imageFromUrl" alt="alert" width="200" height="200">
</div>
</template>
<script>
export default {
data: () => ({
imageFromUrl: null
}),
mounted() {
setTimeout(() => {
this.requestImage()
}, 2000);
},
methods: {
requestImage() {
const responseFromNetwork = 'https://upload.wikimedia.org/wikipedia/commons/thumb/1/12/Google_Photos_icon_%282020%29.svg/1024px-Google_Photos_icon_%282020%29.svg.png'
this.imageFromUrl = responseFromNetwork
}
}
}
</script>
Related
I have a child component that has an input field that is hidden behind a slotted element. The parent will provide the slotted click event element, but also show a preview of the file(s), with the ability to delete them above.
I'm not sure how to work this select and preview functionality when working between a child/parent relationship.
What I have below is as far as I got, but I'm just confused at this point as to where to go.
The slot works to trigger the event in the child, but I get a "TypeError: Failed to execute 'readAsDataURL' on 'FileReader': parameter 1 is not of type 'Blob'." when trying to actually get things to render as currently written.
Where am I going wrong with this?
If you need anymore information please let me know! Cheer!
NOTE: I also need to make this compatitible with V-model, but I don't know how to do that currently.
UploadMediaFiles (Child Component)
<template>
<div class="upload-media-files">
<input
id="input-file"
type="file"
accept="*"
multiple
#change="addMedia"
class="_add-media-input"
ref="input"
/>
<label for="input-file">
<slot :openFileDialog="openFileDialog">
<img
src="https://www.clipartmax.com/png/middle/142-1422132_png-file-svg-upload-file-icon-png.png"
alt=""
/>
</slot>
</label>
</div>
</template>
<style lang="sass" scoped>
input
display: none
</style>
<script>
export default {
name: 'UploadMediaFiles',
props: {
multiple: { type: Boolean },
accept: { type: String },
},
data() {
return {
files: [],
}
},
computed: {},
methods: {
async addMedia(event) {
const files = event.target.files || event.dataTransfer.files
if (!files.length) return
console.log(`files → `, files)
this.files.push(files)
this.$emit('selected', this.files)
},
openFileDialog() {
this.$refs.input.click()
},
},
}
</script>
SelectAndPreviewFiles (Parent Component)
<template>
<div class="select-and-preview-files">
<div v-if="selectedFiles">
<div :key="index" v-for="(selectedFile, index) in selectedFiles">
<img :src="selectedFile" alt="" />
<button #click="deleteFile(index)">Delete</button>
</div>
</div>
<!-- <img />
//OR
<video /> -->
<!-- <img :src="selectedFile" alt="" />-->
<UploadMediaFiles #selected="(files) => selectFiles(files)" v-slot="{ openFileDialog }">
<button #click="openFileDialog">
<img
src="https://upload.wikimedia.org/wikipedia/commons/thumb/a/a1/Circle-icons-upload.svg/1200px-Circle-icons-upload.svg.png"
alt=""
/>
</button>
</UploadMediaFiles>
</div>
</template>
<style lang="sass" scoped>
img
width: 20%
margin: auto
display: block
margin-bottom: 10px
</style>
<script>
import UploadMediaFiles from '../atoms/UploadMediaFiles.vue'
export default {
name: 'SelectAndPreviewFiles',
components: {
UploadMediaFiles,
},
props: {},
data() {
return {
selectedFiles: [],
}
},
computed: {},
methods: {
selectFiles(files) {
this.selectedFiles.push(files)
this.previewImage(files)
},
previewImage(files) {
var vm = this
for (var index = 0; index < files.length; index++) {
var reader = new FileReader()
reader.onload = function (event) {
const imageUrl = event.target.result
vm.files.push(imageUrl)
}
reader.readAsDataURL(files[index])
}
},
deleteFile(index) {
this.selectedFiles.splice(index, 1)
},
},
}
</script>
CodePen without the parent-child relationship
https://codepen.io/LovelyAndy/pen/gOmYGKO?editors=0001
The problem is the input value for multiple selected files is an array of FileLists, which itself is a list of File objects. However, previewImage() seems to assume that the value is an array of File objects.
files[index] is actually a FileList, which is not an acceptable argument to reader.readAsDataURL(), leading to the error.
To resolve the issue, iterate each FileList in the array:
export default {
methods: {
selectFiles(files) {
this.selectedFiles.push(files);
this.previewImage(files);
},
previewImage(files) {
var vm = this
for (var index = 0; index < files.length; index++) {
const fileList = files[index]
fileList.forEach(file => {
var reader = new FileReader()
reader.onload = function (event) {
const imageUrl = event.target.result
vm.selectedFiles.push(imageUrl)
}
reader.readAsDataURL(file)
})
}
},
}
}
demo
I am new to vue and I am trying to call the APOD (Astronomy picture of the day) from NASA so that I can display a new picture every day. I am making a new Vue component called Picture.vue where I do all of the accessing of the APOD api. I have been able to get the proper url for the picture I want to display from the response payload (and store in a variable called 'apod') but simply put I don't know how to put the "apod" variable as a 'src' value into either a regular HTML 'img' tag or a vuetify 'v-img' tag. I have a feeling this could be solved with v-bind but like I said I am new to Vue so any tips or guidance would be most appreciated.
Picture.vue
<section class="picture">
<h1>picture Component</h1>
<v-img src="{{apod}}"></v-img>
</section>
</template>
<script lang="js">
const url = "https://api.nasa.gov/planetary/apod?api_key=" + process.env.VUE_APP_KEY;
const axios = require('axios');
export default {
name: 'picture',
props: [],
async created () {
console.log("https://api.nasa.gov/planetary/apod?api_key=" + process.env.VUE_APP_KEY);
// axios.get(url)
// .then(response => this.apod = response.data.url);
const response = await axios.get(url);
this.apod = response.data.url;
console.log(response);
},
data () {
return {
apod: null
}
},
methods: {
},
computed: {
},
state () {
},
}
</script>
<style scoped lang="scss">
.picture {
}
</style>
App.vue
<template>
<v-app>
<Picture></Picture>
</v-app>
</template>
<script>
import Picture from './components/Picture'
export default {
name: 'App',
components: {
Picture,
},
data() {
return {
}
}
};
</script>
In summary my question is how can I put the 'apod' variable as the value of 'src' in an image tag (Vuetify or HTML)?
Thanks very much everyone happy easter!
Use :src and remove the {{ }}
like this
<v-img :src="this.apod" />
I have a button in vue component within template as follow:
<a href="#" #click="openTab" class="border-red px-8" id="activeSlide" data-target-quote="#yvoefrance">
<img :src="inactive_logo[0]" class="logo" alt="yvoefrance logo" />
</a>
I want it to be clicked by default when components loads after refreshing the page, how can I achieve this? I tried following but didn't work for me.
I thought the right place is created. Can anyone help? Thank you in advance.
export default {
name: "component.showcase",
components: {
// ...
},
data() {
return {
// data here....
};
},
created() {
document.querySelector("#activeSlide").click();
},
mounted() {},
beforeDestroy() {},
computed: {},
methods: {
openTab: function(e) {
e.preventDefault();
const target_tab = e.target.parentElement.dataset.targetQuote;
document.querySelector(target_tab).classList.add("active");
e.target.src = require(`#/assets/img/testimonials/${target_img}_active.png`);
}
}
};
The button should call a method when clicked:
<button #click="someMethod">Show Content</button>
Then you can just call that method programmatically from a lifecycle hook instead of trying to manually trigger a click on the button:
methods: {
someMethod() {
console.log('someMethod called');
}
},
created() {
this.someMethod(); // Run the button's method when created
}
EDIT to match your edit:
You are using DOM manipulation but should manipulate data instead and let Vue handle the DOM. Here is a basic example of how you can do what you want:
new Vue({
el: "#app",
data() {
return {
logos: [
{
urlInactive: 'https://via.placeholder.com/150/000000/FFFFFF',
urlActive: 'https://via.placeholder.com/150/FFFFFF/000000',
isActive: false
},
{
urlInactive: 'https://via.placeholder.com/150/666666/FFFFFF',
urlActive: 'https://via.placeholder.com/150/999999/000000',
isActive: false
}
]
}
},
methods: {
toggleActive(logo) {
logo.isActive = !logo.isActive;
}
},
});
<div id="app">
<a v-for="logo in logos" #click="toggleActive(logo)">
<img :src="logo.isActive ? logo.urlActive : logo.urlInactive" />
</a>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
I am using regular Vue.js in my project. I store data in a store made from scratch and use it in a template:
<template>
<div>
<div class="row">
<div v-for="(picture, index) in storeState.pictures"
:key="index"
class="col-md-2 my-auto">
<div >
<img class="img-thumbnail img-responsive"
:src="picture.url"
#click="deleteMe">
</div>
</div>
</div>
</div>
</template>
<script>
import { store } from "../common/store.js"
export default {
name:"PictureUpload",
data() {
return {
storeState: store.state,
};
},
methods: {
deleteMe() {
let apiUrl = this.picture.url
console.log(apiUrl)
}
}
}
</script>
My pictures are rendering well but now I want to add a delete() function to the picture #click and whenever I click on the button I get:
TypeError: Cannot read property 'url' of undefined
So how can I access my picture data inside my method?
You should pass picture as parameter in the click handler :
#click="deleteMe(picture)">
and refer to it in the method like :
methods: {
deleteMe(picture) {
let apiUrl = picture.url //omit this
console.log(apiUrl)
}
}
the storeState should be a computed property :
export default {
name:"PictureUpload",
data() {
return {
};
},
computed:{
storeState(){
return store.state;
}
},
methods: {
deleteMe(picture) {
let apiUrl = picture.url
console.log(apiUrl)
}
}
}
I am trying to load an inline svg into my component.
App.vue
template
<vue-anime :url="'planetiaermma.svg'" />
anime.vue
<div>
<div v-html="this.loadSVG()"></div>
<img :src="this.svgfile()" alt />
</div>
props: ["url"],
methods: {
svgfile() {
var img = this.getImgUrl(this.url);
return img;
},
getImgUrl(pic) {
return require("../assets/" + pic);
},
loadSVG() {
var img = this.getImgUrl(this.url);
var svgraw;
this.$nextTick(() => {
fetch(img)
.then(res => res.text())
.then(svg => {
svgraw = svg;
});
});
return svgraw;
},
mounted() {
this.loadSVG();
}
}
};
firing svgfile() into a :src works
firing loadSVG() should load it inline, does not seem to however, even though the return svgraw; is in a string of html/xml.
You can simply use something like vue-inline-svg for this:
npm install vue-inline-svg
and register the component globally in your main.js file:
import Vue from 'vue'
import App from './App.vue'
import InlineSvg from 'vue-inline-svg';
Vue.component('inline-svg', InlineSvg);
new Vue({
render: h => h(App),
}).$mount('#app')
After that you can use the component anywhere inside your templates
Note: if you use vue-loader assets or vue-cli, then paths like '../assets/my.svg' will not be handled by file-loader automatically like vue-cli do for tag, so you will need to use it with require:
<template>
<div>
<inline-svg :src="require(`../assets/${url}`)" />
<!-- You also can specify some props -->
<!-- width="150" -->
<!-- height="150" -->
<!-- :fill="false" -->
</div>
</template>
and get rid of that messy code.
I'm not sure what are you getting from getImgUrl() but could you try this?
mounted() {
this.$nextTick(() => {
this.loadSVG();
});
}
You might also try this to be sure it's not from missing value:
<img v-if="svgURL" :src="svgURL" alt />
data() {
return {
svgURL: null
}
}
mounted() {
loadSVG() {
this.svgURL = 'YOUR VALUE'
}
}
Please avoid using this inside the template.
App.vue
<vue-anime :url="'planet.svg'" />
anime.vue component
<template>
<div>
<div v-html="mysvgfile"></div>
</div>
</template>
export default {
props: ["url"],
data() {
return {
mysvgfile: ""
};
},
methods: {
svgfile() {
var img = this.getImgUrl(this.url);
return img;
},
getImgUrl(pic) {
return require("../assets/" + pic);
},
loadSVG() {
var img = this.getImgUrl(this.url);
var outer = this;
this.$nextTick(() => {
fetch(img)
.then(res => res.text())
.then(svg => {
outer.mysvgfile = svg;
});
});
}
},
mounted() {
this.loadSVG();
}
};