When you click on "Choose file" and select an image for upload, the path however appears. The image gets uploaded only after you click "Choose file" one more time.
How to resolve this and upload as and when the file is chosen?
Any help would be much appreciated. Thank you.
new Vue({
el: '.app',
data: {
userImage: ''
},
methods: {
onFileChange(e) {
var files = e.target.files || e.dataTransfer.files
if (!files.length) {
return
}
this.createImage(files[0])
},
createImage(file) {
var reader = new FileReader()
var vm = this
reader.onload = (e) => {
vm.userImage = e.target.result
}
reader.readAsDataURL(file)
},
removeImage: function (e) {
this.userImage = ''
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.2/vue.min.js"></script>
<div class="col-xl-3 col-lg-3 col-md-4 col-sm-6 col-xs-6 text-center app">
<img class="profile-image" :src="userImage" />
<div v-if="!userImage">
<input type="file" round class="change-profile-image" #change="onFileChange" />
</div>
<div v-else>
<button class="delete-profile-image" color="secondary" icon="delete" #click="removeImage">Delete</button>
</div>
</div>
My code on JSfiddle.
You shouldn't rely on listening to the click event. What you are looking for is the change event instead, i.e. use #change instead of #click:
<input type="file" round class="change-profile-image" #change="onFileChange" />
See updated fiddle: https://jsfiddle.net/hrtzezk8/5/, or the proof-of-concept snippet below:
new Vue({
el: '.app',
data: {
userImage: ''
},
methods: {
onFileChange(e) {
var files = e.target.files || e.dataTransfer.files
if (!files.length) {
return
}
this.createImage(files[0])
},
createImage(file) {
var reader = new FileReader()
var vm = this
reader.onload = (e) => {
vm.userImage = e.target.result
}
reader.readAsDataURL(file)
},
removeImage: function (e) {
this.userImage = ''
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.2/vue.min.js"></script>
<div class="col-xl-3 col-lg-3 col-md-4 col-sm-6 col-xs-6 text-center app">
<img class="profile-image" :src="userImage" />
<div v-if="!userImage">
<input type="file" round class="change-profile-image" #change="onFileChange" />
</div>
<div v-else>
<button class="delete-profile-image" color="secondary" icon="delete" #click="removeImage">Delete</button>
</div>
</div>
Related
I'm starting with VueJs.
I would like to combine animation in and out in a modal.
I think I should do a function but can't find how to.
Here my code:
<template>
<div class="backgroundImage" :style="{'background-image': 'url(' + require('../../assets/bkg.jpg') + ')'}">
<div v-if="showModal" #click="showModal = false"></div>
<div class="modal" v-if="showModal">
<div class="animate__animated animate__bounceIn animate__slow">
<img id="synthesisFt" src="../../assets/popup-ftt.jpg" alt="Logo FunkTheTown" title="FunkTheTown" #click="showModal = false"/>
</div>
</div>
<div>
<img class="logo-img" src="../../assets/logo.png" alt="Logo FunkTheTown" title="FunkTheTown" />
</div>
</div>
</template>
<script>
export default {
data () {
return {
showModal: false
}
},
mounted:function(){
this.popup()
},
methods: {
popup : function () {
setTimeout(() => {
this.showModal = true;
}, 3000);
},
// classChange : function () {
// showmodal = false;
// }
}
}
for the off I would like to use animate__animated animate__bounceOut when I click on the modal.
I've resolved the issue, here the code :
<template>
<div class="backgroundImage" :style="{'background-image': 'url(' + require('../../assets/bkg.jpg') + ')'}">
<div v-if="showModal" #click="showModal = false"></div>
<div class="modal" v-if="showModal">
<div class="animate__animated animate__bounceIn animate__slow">
<img id="synthesisFt" src="../../assets/popup-ftt.jpg" alt="Logo FunkTheTown" title="FunkTheTown" #click="anim2()"/>
</div>
</div>
<div class="animate__animated animate__backInDown animate__slow" v-if="showModalLogin">
<div class="modalLogin">
<label>Login</label>
<input class="loginInput" type="text" placeholder="email...">
<label>Password</label>
<input class="loginPassword" type="password" placeholder="password...">
<button class="connexion">Connexion</button>
<button class="join">Join</button>
</div>
</div>
<div>
<img class="logo-img" src="../../assets/logo.png" alt="Logo FunkTheTown" title="FunkTheTown" />
</div>
<div class="animate__animated animate__rotateIn" v-if="showModalLogo" >
<img class="full_logo" src="../../assets/F2T_logo_color.png" >
</div>
<div class="animate__animated animate__rotateIn" v-if="showModalLogo">
<img class="full_logo_right" src="../../assets/F2T_logo_coloreverse.png" >
</div>
</div>
</template>
<script>
export default {
data () {
return {
showModal: false,
showModalLogin: false,
showModalLogo:false,
}
},
mounted:function(){
this.popup()
},
methods: {
popup : function () {
setTimeout(() => {
this.showModal = true;
}, 3000);
},
anim2 : function () {
this.showModal= false;
this.showModalLogin= true;
this.showModalLogo =true;
const element = document.querySelector('.logo-img');
element.classList.add('animate__animated','animate__bounceOut');
}
// classChange : function () {
// showmodal = false;
// }
}
}
I'm a vue js newbie, I perform a get operation with the value entered in the search input and if there is a result, I show it in "listShow", if there is no result, I return "listShow" false. no problem so far. only if the user chooses any of the incoming data, I send the "name" searchtext of the incoming data to the input. but if there is no result "listShow false" and click somewhere outside the input
I want to make "newDiv" true. so "inputOutClick" does the job, but when I click on any of the "search" data, "inputOutClick" does not allow this "selecteds()" function to fire.
And also, is my coding style correct, I'm getting too repetitive.
Is it ok to use search #keyup?
Does it make sense to use v-on:focusout?
const app = new Vue({
el: '#app',
data: {
searchText: '',
listShow: true,
newDiv:false,
searcList:[],
},
methods: {
inputOutClick() {
this.listShow = false
},
selecteds(list) {
this.listShow = false;
this.searchText = list.name;
},
async search() {
if (this.searchText !== '') {
const res = await this.callApi('get', 'search' + '?filter=' + this.searchText)
if (res.status === 200) {
this.searcList = this.getList;
if (res.data.length > 0) {
this.listShow = true;
} else {
this.listShow = false;
}
}
} else {
this.listShow = false;
}
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.4.2/vue.js"></script>
<div id="app">
<div>
<input
type="text"
v-model="searchText"
#keyup="search"
v-on:focusout="inputOutClick"
/>
<div v-if="listShow" style="background:red">
<ul>
<li v-for="(list, index) in searcList">
<a #click="selecteds(list)">{{ list.name }}</a>
</li>
</ul>
</div>
<div v-if="newDiv">
<p>hello</p>
</div>
</div>
</div>
You can use #mousedown.prevent on the searchList entries (where the click handler is attached). This prevents the v-on:focusout event being fired, if a searchList entry is clicked.
<input
type="text"
v-model="searchText"
#keyup="search"
v-on:focusout="inputOutClick"
/>
<a
#click="selectEntry(entry)"
#mousedown.prevent
>
xxx
</a>
Use #mousedown instead of #click.
=> #click runs after #focusout.
=> #mousedown runs before #focusout.
If you do not want to run the focusout function on the input field when the list is clicked at all then you can use #mousedown.prevent="selecteds(list)".
See example below (click on "Full page" so the console.log doesn't block the list):
const app = new Vue({
el: '#app',
data: {
searchText: '',
listShow: true,
newDiv:false,
searcList:[],
list: {}
},
methods: {
inputOutClick() {
console.log("inputOutClick");
if (this.listShow == false) {
console.log("mousedown was fired first");
}
this.listShow = false
},
selecteds(list) {
console.log("selecteds");
this.listShow = false;
this.searchText = list.name;
},
async search() {
console.log("search");
this.listShow = true;
this.searcList = ['aeaeg', 'tdthtdht', 'srgsr'];
this.list.name = "TEST"
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.4.2/vue.js"></script>
<div id="app">
<div>
<input
type="text"
v-model="searchText"
#keyup="search"
v-on:focusout="inputOutClick"
/>
<div v-if="listShow" style="background:red">
<ul>
<li v-for="(list, index) in searcList">
<a #mousedown="selecteds(list)">LIST TEXT</a>
</li>
</ul>
</div>
<div v-if="newDiv">
<p>hello</p>
</div>
</div>
</div>
im have little problem with clean input after functions complete
Can someone tell me what im do wrong
After functions is complete im try to clean the input
But i dont have any result with this
this is my code in Vue Component
<form role="form">
<div class="card-body">
<div class="form-group">
<label for="file">Upload File</label>
<div class="input-group">
<div class="custom-file">
<input
type="file"
class="custom-file-input"
id="file"
ref="file"
v-on:change="handleFileUpload"
/>
<label class="custom-file-label" for="file">Choose file</label>
</div>
</div>
</div>
</div>
<div class="card-footer">
<button v-on:click="onClickUploadAccounts" class="btn btn-primary">Upload</button>
<button v-on:click="onClickSetLoader" class="btn btn-primary">Loader</button>
</div>
</form>
methods: {
handleFileUpload(){
this.file = this.$refs.file.files[0]
},
onClickUploadAccounts(){
let formData = new FormData();
formData.append('file', this.file);
this.$store.commit('imports/setIsLoad', true)
axios.post( '/admin-account-import',
formData,
{
headers: {
'Content-Type': 'multipart/form-data'
}
}
).then(() => {
console.log('SUCCESS!!')
this.$store.commit('imports/setIsLoad', false)
this.file = ''
formData.delete('file')
formData.append('file', this.file = '')
})
.catch(() => {
console.log('FAILURE!!');
});
},
onClickSetLoader()
{
this.$refs.file.files = ''
},
},
You need to set this.file to null. in your data
data: function () {
return {
file: null
}
}
And you can remove in your methods
this.file = ''
formData.delete('file')
formData.append('file', this.file = '')
I have a web page that displays items. For each items there is a button (vuejs component) which allow user to toggle (add/remove) this item to his collection.
Here is the component:
<template lang="html">
<button type="button" #click="toggle" name="button" class="btn" :class="{'btn-danger': dAdded, 'btn-primary': !dAdded}">{{ dText }}</button>
</template>
<script>
export default {
props: {
added: Boolean,
text: String,
id: Number,
},
data() {
return {
dAdded: this.added,
dText: this.text,
dId: this.id
}
},
watch: {
added: function(newVal, oldVal) { // watch it
this.dAdded = this.added
},
text: function(newVal, oldVal) { // watch it
this.dText = this.text
},
id: function(newVal, oldVal) { // watch it
this.dId = this.id
}
},
methods: {
toggle: function(event) {
axios.post(route('frontend.user.profile.pop.toggle', {
pop_id: this.dId
}))
.then(response => {
this.dText = response.data.message
let success = response.data.success
this.dText = response.data.new_text
if (success) {
this.dAdded = success.attached.length
let cardPop = document.getElementById('card-pop-'+this.dId);
if(cardPop)
cardPop.classList.toggle('owned')
}
})
.catch(e => {
console.log(e)
})
}
}
}
</script>
For each item, the user can also open a modal, loaded by a click on this link:
<a href="#" data-toggle="modal" data-target="#popModal" #click="id = {{$pop->id}}">
<figure>
<img class="card-img-top" src="{{ URL::asset($pop->img_path) }}" alt="Card image cap">
</figure>
</a>
The modal is also a Vuejs component:
<template>
<section id="pop" class="h-100">
<div class="card">
<div class="container-fluid">
<div class="row">
<div class="col-12 col-lg-1 flex-column others d-none d-xl-block">
<div class="row flex-column h-100">
<div v-for="other_pop in pop.other_pops" class="col">
<a :href="route('frontend.pop.collection.detail', {collection: pop.collection.slug, pop: other_pop.slug})">
<img :src="other_pop.img_path" :alt="'{{ other_pop.name }}'" class="img-fluid">
</a>
</div>
<div class="col active order-3">
<img :src="pop.img_path" :alt="pop.name" class="img-fluid">
</div>
</div>
</div>
<div class="col-12 col-lg-6 content text-center">
<div class="row">
<div class="col-12">
<img :src="pop.img_path" :alt="pop.name" class="img-fluid">
</div>
<div class="col-6 text-right">
<toggle-pop :id="pop.id" :added="pop.in_user_collection" :text="pop.in_user_collection ? 'Supprimer' : 'Ajouter'"></toggle-pop>
</div>
<div class="col-6 text-left">
<!-- <btnaddpopwhishlist :pop_id="propid" :added="pop.in_user_whishlist" :text="pop.in_user_whishlist ? 'Supprimer' : 'Ajouter'"></btnaddpopwhishlist> -->
</div>
</div>
</div>
<div class="col-12 col-lg-5 infos">
<div class="header">
<h1 class="h-100">{{ pop.name }}</h1>
</div>
<div class="card yellow">
<div class="card p-0">
<div class="container-fluid">
<div class="row">
<div class="col-3 py-2">
</div>
<div class="col-6 py-2 bg-lightgray">
<h4>Collection:</h4>
<h3>{{ pop.collection ? pop.collection.name : '' }}</h3>
</div>
<div class="col-3 py-2 bg-lightgray text-center">
<a :href="route('frontend.index') + 'collections/' + pop.collection.slug" class="btn-round right white"></a>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</section>
</template>
<script>
export default {
props: {
id: Number
},
data() {
return {
pop: {
collection: {
}
}
}
},
ready: function() {
if (this.propid != -1)
this.fetchData()
},
watch: {
id: function(newVal, oldVal) { // watch it
// console.log('Prop changed: ', newVal, ' | was: ', oldVal)
this.fetchData()
}
},
computed: {
imgSrc: function() {
if (this.pop.img_path)
return 'storage/images/pops/' + this.pop.img_path
else
return ''
}
},
methods: {
fetchData() {
axios.get(route('frontend.api.v1.pops.show', this.id))
.then(response => {
// JSON responses are automatically parsed.
// console.log(response.data.data.collection)
this.pop = response.data.data
})
.catch(e => {
this.errors.push(e)
})
// console.log('fetchData')
}
}
}
</script>
Here is my app.js script :
window.Vue = require('vue');
Vue.component('pop-modal', require('./components/PopModal.vue'));
Vue.component('toggle-pop', require('./components/TogglePop.vue'));
const app = new Vue({
el: '#app',
props: {
id: Number
}
});
I would like to sync the states of the component named toggle-pop, how can I achieve this ? One is rendered by Blade template (laravel) and the other one by pop-modal component. But they are just the same, displayed at different places.
Thanks.
You could pass a state object as a property to the toggle-pop components. They could use this property to store/modify their state. In this way you can have multiple sets of components sharing state.
Your component could become:
<template lang="html">
<button type="button" #click="toggle" name="button" class="btn" :class="{'btn-danger': sstate.added, 'btn-primary': !sstate.added}">{{ sstate.text }}</button>
</template>
<script>
export default {
props: {
sstate: {
type: Object,
default: function() {
return { added: false, text: "", id: -1 };
}
}
},
data() {
return {};
},
methods: {
toggle: function(event) {
axios.post(route('frontend.user.profile.pop.toggle', {
pop_id: this.sstate.id
}))
.then(response => {
this.sstate.text = response.data.message
let success = response.data.success
this.sstate.text = response.data.new_text
if (success) {
this.sstate.ddded = success.attached.length
let cardPop = document.getElementById('card-pop-'+this.sstate.id);
if(cardPop)
cardPop.classList.toggle('owned')
}
})
.catch(e => {
console.log(e)
})
}
};
</script>
Live demo
https://codesandbox.io/s/vq8r33o1w7
If you are 100% sure that all toggle-pop components should always have the same state, you can choose to not define data as a function. Just declare it as an object.
data: {
dAdded: this.added,
dText: this.text,
dId: this.id
}
In https://v2.vuejs.org/v2/guide/components.html#data-Must-Be-a-Function, it mentions
a component’s data option must be a function, so that each instance
can maintain an independent copy of the returned data object
If Vue didn’t have this rule, clicking on one button would affect the
data of all other instances
Since you want to sync the data of all toggle-pop component instances, you don't have to follow the data option must be a function rule.
My vue component like this :
<template>
<div class="modal" tabindex="-1" role="dialog">
...
<div class="form-group">
<label for="change-image">Change image</label>
<input type="file" name="replace" v-on:change="changeImage">
</div>
<div class="form-group">
<label for="alt-image">Alt attr</label>
<input type="text" class="form-control" v-model="altImage">
</div>
<div class="checkbox">
<label>
<input type="checkbox" v-model="mainCover"> Set Cover
</label>
</div>
<button type="button" class="btn btn-success" #click="editImageProduct">
Edit
</button>
...
</div>
</template>
<script>
export default{
...
data() { return {altImage: '', mainCover: '', imageChanged: '', image: ''}},
methods: {
editImageProduct(event) {
const payload = {alt_image: this.altImage, main_cover: this.mainCover, image_changed: this.imageChanged}
this.$store.dispatch('editImageProduct', payload)
},
changeImage(e) {
var files = e.target.files || e.dataTransfer.files
if (!files.length)
return;
this.createImage(files[0])
this.imageChanged = files[0]
},
createImage(file) {
var image = new Image()
var reader = new FileReader()
var vm = this
reader.onload = (e) => {
vm.image = e.target.result
};
reader.readAsDataURL(file)
},
}
}
</script>
I want to send the parameters to controller. It will go through modules, api, routes and controller
On the controller, I do like this :
public function editImage(Request $request)
{
dd($request->all());
}
When executed, the result like this :
array:5 [
"alt_image" => "test alt"
"main_cover" => true
"image_changed" => []
]
The param image_changed is empty
Whereas on the component, I do console.log, it display the result
When I do console.log(files[0]), the result like this :
How can I solve this problem?