I would like to call a method from a concatenated checkbox.
here is my code:
methods: {
listServices(serviceId) {
axios
.get(
process.env.ROOT_API + "Service/List?Id=" + serviceId,
this.$store.getters.getTokenHeaderFormData
)
.then(response => {
response.data.forEach(el => {
this.dataset.push([
el.serviceName,
`<input type="checkbox"
onchange="${this.updateService(el.ServiceId)}">` // <-- Call UpdateService method
]);
});
})
.catch(error => {
console.log(error);
});
},
updateService(serviceId){
console.log(serviceId);
},
The onchange="${this.updateService(el.ServiceId)}" does not work. how can I do this?
The proper way to do this is to use v-for:
<template>
<ul>
<li v-for="item in dataset" :key="item[1]">
<input type="checkbox" #change="updateService(item[1])">
</li>
</ul>
</template>
<script>
export default
{
methods:
{
listServices(serviceId)
{
axios.get(
process.env.ROOT_API + "Service/List?Id=" + serviceId,
this.$store.getters.getTokenHeaderFormData
).then(response =>
{
response.data.forEach(el =>
{
this.dataset.push([
el.serviceName,
el.ServiceId
]);
});
}).catch(error =>
{
console.log(error);
});
},
updateService(serviceId)
{
console.log(serviceId);
},
}
}
</script>
Related
I am fetching my data from external API link and I would like to filter them - live searching, so when I type a letter, the results that includes that letter will get filtered.
For now I am not able to do it and when I click into my input I just get all the results printed out and nothing is happening when I am trying to filter them.
This is my logic in script:
data() {
return {
result: "",
modal: false,
results: [],
filteredResults: [],
};
},
mounted() {
axios
.get("secretDataURL")
.then((response) => {
this.filteredResults = response.data;
})
.catch((error) => (this.filteredResults = console.log(error)))
.finally(() => console.log("Data successfully loaded"));
},
methods: {
filterResults() {
if (this.result.lenght == 0) {
this.filteredResults = this.results;
}
this.filteredResults = this.results.filter((result) => {
return result.toLowerCase().startsWith(this.result.toLowerCase());
});
},
setResult(result) {
this.result = result;
this.modal = false;
},
},
watch: {
state() {
this.filterResults();
},
}
And my template
<div #click="modal = false"></div>
<input
type="text"
v-model="result"
autocomplete="off"
#input="filterResults"
#focus="modal = true"
/>
<div v-if="filteredResults && modal">
<ul>
<li
v-for="(filteredResult, index) in filteredResults"
:key="index"
#click="setResult(filteredResult)"
>
{{ filteredResult.name }}
</li>
</ul>
</div>
How can I make it work, where my logic is failing ?
U get the data in hook mounted.
And then lost it.
Change this.filteredResults = response.data; to this.results = response.data;
I'm trying to consume an API using axios.
This is my code untill now
<select>
<option v-for="value in values"> value.name </option>
</select>
// js
data(){
values: [],
},
created() {
this.getData();
},
methods: {
getData: () => {
axios.get('url')
.then(res => {
this.value = res.data.dados;
console.log(res.data.dados);
})
.catch(error => {
console.log(error);
});
}
}
The promise's console.log is working normally, but the options with data isn't rendered.
It's probably because my select component is being rendered before the 'getData()'. How can I fix it?
Just put a loading handler.
<select v-if="loaded">
<option v-for="value in values"> value.name </option>
</select>
// js
data(){
values: [],
loaded: false,
},
created() {
this.getData();
},
methods: {
getData: () => {
axios.get('url')
.then(res => {
this.value = res.data.dados;
this.loaded = true;
})
.catch(error => {
console.log(error);
this.loaded = true;
});
}
}
You've a typo on this.value, it should be this.values. If that doesn't work, use this.$forceUpdate() to force re-render component
<select>
<option v-for="value in values">{{ value.name }}</option>
</select>
// js
data(){
values: [],
},
created() {
this.getData();
},
methods: {
getData: () => {
axios.get('url')
.then(res => {
this.values = res.data.dados; // change value to values
console.log(res.data.dados);
this.$forceUpdate(); // add forceUpdate
})
.catch(error => {
console.log(error);
});
}
}
<template>
<div class="comment">
<div v-for="(comment, index) in comments" :key="index">
{{ getUser(comment.student_idx) }}
</div>
</div>
</template>
<script>
import axios from 'axios'
import server from '#/models/server'
export default {
data() {
return {
url: server,
comments: {}
}
},
props: ['idx'],
created() {
axios.get(`${this.url}/bamboo/reply?post=${this.idx}`)
.then(response => {
if (response.data.status === 200) {
this.comments = response.data.data.replies
}
})
},
methods: {
getUser (idx) {
axios.get(`${this.url}/member/student/${idx}`)
.then(response => {
if (response.data.status === 200) {
return response.data.data.member.name
}
})
}
}
}
</script>
I would like to load the comments at created and print them out using v-for.
In v-for, I would like to load the member.name from each comment
But {{ getUser(comment.student_idx) }} is undefined.
I don't know how to return data from axios
Help me please!!
Your method should not be async for stable run code. My recomendation is next code:
<template>
<div class="comment">
<div v-for="(comment, index) in comments" :key="index">
{{ comments['user'] }}
</div>
</div>
</template>
<script>
import axios from 'axios'
import server from '#/models/server'
export default {
data() {
return {
url: server,
comments: []
}
},
props: ['idx'],
created() {
axios.get(`${this.url}/bamboo/reply?post=${this.idx}`)
.then(response => {
if (response.data.status === 200) {
this.comments = response.data.data.replies;
if(this.comments)
for(let comment of this.comments){
this.getUser(comment, comment.student_idx);
}
}
})
},
methods: {
getUser (comment, idx) {
axios.get(`${this.url}/member/student/${idx}`)
.then(response => {
if (response.data.status === 200) {
this.$set(comment, 'user', response.data.data.member.name);
}
})
}
}
}
</script>
I am trying to use HTML's datalist [https://www.w3schools.com/tags/tag_datalist.asp] element rather than an autocompletion library. I tried to wrap an a href element around the post.title.
Unfortunately, it looks like this is not possible with the datalist's option element?
Here's my template:
<input v-model='post' type='text' list='posts'>
<datalist id='posts'>
<option v-for='post in posts' :key='post.id'>
<a :href='url + `${post.id}`'>{{post.title}}</a>
</option>
</datalist>
Script:
import axios from "axios";
export default {
name: "SearchBar",
data() {
return {
post: "",
posts: [],
url: "https://jsonplaceholder.typicode.com/posts/",
//placeholder: "Search or jump to item"
};
},
created() {
this.getPosts();
},
methods: {
getPosts() {
axios
.get("https://jsonplaceholder.typicode.com/posts")
.then(response => {
console.log(response);
this.posts = response.data;
})
.catch(error => {
console.log(error);
});
}
}
};
Anyone got some workarounds for this? Thank you
friend.
if you want to check.
regards!
Here's a link!
new Vue({
el: "#app",
data() {
return {
posts: []
}
},
created() {
this.getPosts()
},
methods: {
getPosts() {
axios
.get("https://jsonplaceholder.typicode.com/posts")
.then(response => {
console.log(response);
this.posts = response.data;
})
.catch(error => {
console.log(error);
});
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.18.0/axios.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<input list="posts" name="posts">
<datalist id="posts">
<option v-for="post in posts" :key="post.id" :value="post.title">
{{ post.title }}
</option>
</datalist>
</div>
I have a simple file upload component FileUpload.vue
<template>
<div>
<input type="file" name="file" id="file" v-on:change="handleFileUpload()" ref="file">
<button class="btn shadow-lg first" #click="addFiles()">SELECT FILE</button>
<button class="btn shadow-lg" v-on:click="handleSubmit()">UPLOAD</button>
<p> {{uploadPercentage}} </p>
</div>
</template>
<script>
import axios from 'axios';
export default {
name: 'FileUpload',
data() {
return {
file: '',
uploadPercentage: 0
}
},
methods: {
handleFileUpload: () => {
this.file = document.getElementById('file').files[0];
},
addFiles: () => {
document.getElementById('file').click();
},
handleSubmit: () => {
let formData = new FormData();
formData.append('file', this.file);
axios.post('/file/create',
formData,
{
headers: {
'Content-Type': 'multipart/form-data'
},
onUploadProgress: (progressEvent) => {
console.log(this.uploadPercentage);
this.uploadPercentage = parseInt(Math.round(progressEvent.loaded * 100 / progressEvent.total));
}
}
)
.then((response) => {
console.log(response.data);
})
.catch((error) => {
console.log(error);
})
}
}
}
</script>
The data uploadPercentage is initialized to 0. As the file upload starts, the uploadPercentage value changes in the onUploadProgress method.
If I console log uploadPercentage, it shows the changes in the value. It goes from 0 to 100.
console.log(this.uploadPercentage)
But in my view, uploadPercentage never changes. It always shows the initial value 0.
<p> {{uploadPercentage}} </p>
What am I doing wrong?
Thanks in advance.