Reputation: 11
<input type="file"
id="fieldBoxContentAddPhoto"
accept="image/png"
@input="inputPhoto(this,fieldBoxContentAddPhoto2,fieldBoxContentAddPhoto3)"
>
<img alt=""
ref="fieldBoxContentAddPhoto2"
src="fieldBoxContentAddPhoto3"
style="width:150px;height:150px"
>
const fieldBoxContentAddPhoto2 = ref();
const fieldBoxContentAddPhoto3 = ref();
function inputPhoto(p,p2,p3){
console.log(p); //output is not the input element?
console.log(p2); //output the img element
console.log(p3); //output undefined?
}
1: In HTML oninput event passing 'this' will output the input element, how to do the same in @input?
2: How to output fieldBoxContentAddPhoto3 correctly, so that I can set 'p3.value = xxx;'? I know I can use 'p2.src = xxx;', but in some situations, I need to pass the ref to the function directly. Suppose I having many input+img elements in a page and need to call the same inputPhoto function for doing the same logic.
Upvotes: 0
Views: 135
Reputation: 51
Question 1 Solution: use 'event.target' to get the input element.
Question 2 Solution: Rather than passing params to function directly use reference and by using the '.value' property you can assign value. check below given example.
<template>
<div>
<input type="file" id="fieldBoxContentAddPhoto" accept="image/png" @input="inputPhoto">
<img alt="" ref="fieldBoxContentAddPhoto2" :src="fieldBoxContentAddPhoto3" style="width:150px;height:150px">
</div>
</template>
<script>
import { ref } from 'vue';
export default {
setup() {
const fieldBoxContentAddPhoto2 = ref(null);
const fieldBoxContentAddPhoto3 = ref('');
function inputPhoto(event) {
const inputElement = event.target;
console.log(inputElement);
console.log(fieldBoxContentAddPhoto2.value);
console.log(fieldBoxContentAddPhoto3.value);
const file = inputElement.files[0];
if (file) {
const reader = new FileReader();
reader.onload = function(e) {
fieldBoxContentAddPhoto3.value = e.target.result;
};
reader.readAsDataURL(file);
}
}
return {
fieldBoxContentAddPhoto2,
fieldBoxContentAddPhoto3,
inputPhoto
};
}
};
</script>
Upvotes: 0