Data is not coming if i use async in vue js 3 - vue.js

I am implementing Quiz App but here I am facing an issue if I put static data in array the questions are coming.
Data is not coming if i use async in Vue JS 3
But If I Call data from the API the questions are not showing.
when I console the questions are showing in console and not showing in the front end.
For ref please find the attached code and image.
Home.vue (please see fetchQuestionsFromServer function)
<template>
<main class="flex h-screen items-center justify-center bg-gray-100">
<!-- quiz container -->
<QuizComplatePage v-if="endofQuiz" />
<div
class="overflow-hidden bg-white flex-none container relative shadow-lg rounded-lg px-12 py-6"
>
<img
src="#/assets/images/abstract.svg"
alt=""
class="absolute -top-10 left-0 object-none"
/>
<!-- contents -->
<div class="relative z-20">
<!-- score container -->
<div class="text-right text-gray-800">
<p class="text-sm leading-3">Score</p>
<p class="font-bold">{{score}}</p>
</div>
<!-- timer container -->
<div class="bg-white shadow-lg p-1 rounded-full w-full h-5 mt-4">
<div class="bg-blue-700 rounded-full w-11/12 h-full"
:style= "`width: ${timer}%`"
></div>
</div>
<!-- question container -->
<div
class="rounded-lg bg-gray-100 p-2 neumorph-1 text-center font-bold text-gray-800 mt-8"
>
<div class="bg-white p-5">
{{currentQuestion.question}}
</div>
</div>
<!-- options container -->
<div class="mt-8">
<!-- option container -->
<div v-for="(choice,item) in currentQuestion.choices" :key="item">
<div
class="neumorph-1 option-default bg-gray-100 p-2 rounded-lg mb-3 relative"
:ref="optionchosen"
#click="onOptionClick(choice,item)"
>
<div
class="bg-blue-700 p-1 transform rotate-45 rounded-md h-10 w-10 text-white font-bold absolute right-0 top-0 shadow-md"
>
<p class="transform -rotate-45">+10</p>
</div>
<div class="rounded-lg font-bold flex p-2">
<!-- option ID -->
<div class="p-3 rounded-lg">{{item}}</div>
<!-- option name -->
<div class="flex items-center pl-6">{{choice}}</div>
</div>
</div>
</div>
<!-- option container -->
</div>
<!-- progress indicator container -->
<div class="mt-8 text-center">
<div class="h-1 w-12 bg-gray-800 rounded-full mx-auto"></div>
<p class="font-bold text-gray-800">{{questionCounter}}/{{questions.length}}</p>
</div>
</div>
</div>
</main>
</template>
<script>
import { onMounted, ref } from 'vue'
import QuizComplatePage from './QuizCompleteOverlay.vue'
export default{
components: {
QuizComplatePage
},
setup(){
//data
let canClick = true
let score = ref(0)
let timer = ref(100)
let endofQuiz = ref(false)
let questionCounter = ref(0)
const currentQuestion = ref({
question: '',
answer: 1,
choices: [],
});
const questions = []
const loadQuestion = () =>{
canClick = true
timer.value=100
//Check question array had questions or not
if(questions.length > questionCounter.value){
currentQuestion.value = questions[questionCounter.value]
console.log('Current Question is : ', currentQuestion.value);
questionCounter.value++
}else{
endofQuiz.value = true
console.log('Out of Questions');
}
}
//methods
let itemsRef = []
const optionchosen = (element) =>{
if(element){
itemsRef.push(element)
}
}
const clearSelected = (divselected) =>{
setTimeout(()=>{
divselected.classList.remove('option-correct')
divselected.classList.remove('option-wrong')
divselected.classList.add('option-default')
loadQuestion()
},1000)
}
const onOptionClick = (choice,item) =>{
if(canClick)
{
const divContainer = itemsRef[item]
const optionId = item+1
if(currentQuestion.value.answer ===optionId){
console.log('You are Correct');
score.value += 10
divContainer.classList.add('option-correct')
divContainer.classList.remove('option-default')
}else{
console.log('You are Wrong');
divContainer.classList.add('option-wrong')
divContainer.classList.remove('option-default')
}
timer.value=100
canClick=false
//to go next question
clearSelected(divContainer)
console.log(choice,item);
}else{
console.log('Cant Select Option');
}
}
const countDownTimer = () =>{
let interval= setInterval(()=>{
if(timer.value>0){
timer.value--
}else{
console.log('Time is over');
clearInterval(interval)
}
},150)
}
const fetchQuestionsFromServer = async function(){
fetch('https://opentdb.com/api.php?amount=10&category=18&type=multiple')
.then((res) =>{
return res.json()
})
.then((data) =>{
const newQuestions = data.results.map((serverQuestion) =>{
const arrangedQuestion = {
question: serverQuestion.question,
choices: '',
answer: ''
}
const choices = serverQuestion.incorrect_answers
arrangedQuestion.answer = Math.floor(Math.random() * 4 + 1)
choices.splice(arrangedQuestion.answer-1 , 0 , serverQuestion.correct_answer)
arrangedQuestion.choices = choices
return arrangedQuestion
})
console.log('new formated questions' , newQuestions);
questions.value = newQuestions
loadQuestion()
countDownTimer()
console.log('questions: =>' , questions.value);
})
}
//lifecycle hooks
onMounted(() =>{
fetchQuestionsFromServer()
})
//return
return {
timer,
currentQuestion,
questions,
score,
questionCounter,
loadQuestion,
onOptionClick,
optionchosen,
endofQuiz,
}
}
}
</script>
<style scoped>
.neumorph-1 {
box-shadow: 6px 6px 18px rgba(0, 0, 0, 0.09), -6px -6px 18px #ffffff;
}
.container {
max-width: 400px;
border-radius: 25px;
}
</style>
QuizComplatePage.vue
<template>
<div class="w-screen h-screen absolute z-30 bg-white bg-opacity-30 flex justify-center items-center">
<div class="bg-green-700 p-4 text-center text-white">
<p class="font-bold text-2xl">All DOne!</p>
<p class="my-4 font-bold text-3xl">100% Score</p>
<!-- Buttons -->
<div class="flex justify-center">
<div class="rounded-full py-1 w-28 border cursor-pointer hover:text-black hover:bg-white">Done</div>
<div class="rounded-full py-1 w-28 border cursor-pointer hover:text-black hover:bg-white">Retry</div>
</div>
</div>
</div>
</template>
<script>
export default {
name: 'QuizComplatePage'
}
</script>
<style>
</style>
Image.

You are not using value when you need to:
For instance look in this function
questions.length should be questions.value.length
Also currentQuestion.value = questions.value[questionCounter.value]
Start by fixing that.
Everything that is a ref in your setup needs to be accessed by .value in anything inside your setup. Outside your setup it will have this and can be treated normally. Mixing these two up is the most common error.
const loadQuestion = () =>{
canClick = true
timer.value=100
//Check question array had questions or not
if(questions.value.length > questionCounter.value){
currentQuestion.value = questions.value[questionCounter.value]
console.log('Current Question is : ', currentQuestion.value);
questionCounter.value++
}else{
endofQuiz.value = true
console.log('Out of Questions');
}
}

Here is my solution
let questions = []
questions = newQuestions
Now I am able to load questions.

Related

Vue Computed Value Filter (script setup)

I can't find anything relevant online. The relevant answers online dont use the tag.
Does it even work with script setup?
<template>
<div class="bg-white md:container md:mx-auto w-10">
<ul class="flex flex-wrap p-2 justify-center bg-black text-white">
<li class="p-2">
Filter
</li>
<li class="p-2">
Search
</li>
</ul>
<div class="flex flex-wrap justify-center h-52 content-center">
<div class="flex justify-center">
<div class="mb-3 xl:w-96">
<label
for="exampleSearch2"
class="form-label inline-block mb-2 text-gray-700"
>Search</label
>
<input
v-model="searchValue"
type="search"
class="form-control block w-full px-3 py-1.5 text-base font-normal text-gray-700 bg-white bg-clip-padding border border-solid border-gray-300 rounded transition ease-in-out m-0 focus:text-gray-700 focus:bg-white focus:border-blue-600 focus:outline-none"
id="exampleSearch2"
placeholder="Type query"
/>
<div class="flex flex-wrap">
<div>Test: {{ searchValue }}</div>
</div>
</div>
</div>
</div>
<div class="grid lg:grid-cols-4 md:grid-cols-3 gap-8">
<dogCard v-for="breed in breedsArray" :key="breed.id" :breed="breed" />
</div>
</div>
</template>
<script setup>
import dogCard from "../components/dogCard.vue";
import { ref, onMounted, computed } from "vue";
import searchBox from "./searchBox.vue";
let URL = "https://api.thedogapi.com/v1/breeds";
const searchValue = ref("");
let breedsData = ref([]);
// Fetching API Data
function getBreedsArray() {
fetch(URL)
.then((response) => response.json())
.then((data) => {
breedsData.value = data;
console.log("Data Fetched", breedsData.value);
})
.catch((error) => {
console.error(error);
});
}
onMounted(() => {
getBreedsArray();
});
const breedsArray = computed({
get() {
return breedsData.value;
},
set(val) {
breedsData.value = breedsData.value.filter((breed) => breed.name.includes() == searchValue);
},
});
let isVisible = ref(false);
</script>
Im trying to filter the dogCard through a Searchbox. I just don't know how to do it.
The Data of 'breedsData' should change on when something is entered in the Searchbox.
Thanks in advance, I'm stuck for so long now, an i dont how to fix this.
In the filter() in the computed setter, you do:
(breed) => breed.name.includes() == searchValue
But you probably want to use the value of the ref instead of the ref itself, and put it into includes():
(breed) => breed.name.includes(searchValue.value)
Note that this would permanently remove filtered breeds, as you change the breedsData.value. A better approach might be to just use the computed getter (I don't think the setter works the way you want it to anyway):
const breedsArray = computed(() => searchValue.value ?
breedsData.value.filter( breed => breed.name.includes(searchValue.value)) :
breedsData.value
)
Since searchValue is reactive, a change to it will trigger an update of the breedsArray.

in svelte shows me variable hash in the variables

I have a problem, i am trying to search an element by id in the script but it was not working, when i go to show the values in console, i see that it adds after each variable a random hash, and that is why it does not find the id.
How can I avoid those random hashes?
Svelte
console
I tried different declarations, splits and so on, but it always adds it. Help
<script>
import { page } from '$app/stores';
import { onMount, beforeUpdate } from 'svelte';
import { Line } from 'svelte-chartjs';
import { Chart as ChartJS, Title, Tooltip, Legend, LineElement, LinearScale, PointElement, CategoryScale } from 'chart.js';
ChartJS.register(Title, Tooltip, Legend, LineElement, LinearScale, PointElement, CategoryScale);
export let param = String($page.params.slug);
let ruta_api = `${import.meta.env.VITE_WP_API}posts?slug=${param}`;
let ruta_api_chart = '';
let value = [];
let value_chart = [];
let data_chart = new Array;
let id_chart = '';
onMount(async () => {
await loadData();
});
async function loadData() {
const response = await fetch(ruta_api);
const newData = await response.json();
value = [...value, ...newData];
ifChart();
}
beforeUpdate(async () => {
});
async function ifChart(){
//comprobamos si viene una grafica en el contenido
let posicion_chart = value[0].content.rendered.indexOf('m-chart-container-');
if(posicion_chart >= 0){
console.log(id_chart);
const regex = /(?<=m-chart-container-)(.*?)(?=-)/mg;
console.log(value[0].content.rendered.match(regex)[0]);
id_chart = value[0].content.rendered.match(regex);
//recorremos los ids
id_chart.forEach(function(id) {
getChart(id);
let div_chart = 'm-chart-container-'+id+'-1';
console.log('primero');
console.log({div_chart});
console.log('segundo');
console.log(`${div_chart}`);
console.log('tercero');
console.log(div_chart);
document.getElementById(div_chart).innerHTML = '11111';
})
//<Line data={data_chart} options={{ responsive: true }} />
}
};
export async function getChart(id){
ruta_api_chart = `${import.meta.env.VITE_WP_API}m-chart/` + id;
console.log(ruta_api_chart);
const response_chart = await fetch(ruta_api_chart);
const newData_chart = await response_chart.json();
value_chart = newData_chart['m-chart'];
var datos = value_chart['data'][0][1].filter(n => n).map(Number);
data_chart =
{'labels' : value_chart['data'][0][0].filter(n => n),
'datasets': [{
'label' : 'My First dataset',
'borderColor': 'rgb(205, 130, 158)',
'data' : datos
}]
};
};
</script>
{#each value as article}
<div class="hero" style="background-image: url({article.featured_image_url ? article.featured_image_url : '../img/componentes/blog-img-defecto.png'});">
<div class="hero-overlay bg-opacity-60"></div>
<div class="hero-content text-center text-neutral-content">
<div class="max-w-md">
<h1 class="mb-5 text-5xl font-bold text-secondary">{#html article.title.rendered}</h1>
</div>
</div>
</div>
<div class="w-full mb-32 contenidoblog pt-8">
{#html article.content.rendered}
<div class="flex items-center flex-col my-20">
<button onclick="" class="btn btn-sm border-0 w-40 rounded-full bg-primary font-normal hover:bg-accent text-secondary hover:text-primary transition ease-in-out duration-500 transform hover:scale-105 px-10 mt-4 pr-10 relative">
<span class="absolute left-8">Descargar</span>
<span class="material-symbols-outlined absolute right-8">
download
</span>
</button>
</div>
<!--
<div class="flex items-center flex-col w-full bg-accent h-24">
Bloque post relacionados
</div>
-->
<div class="flex items-center flex-col my-20">
<button onclick="" class="btn btn-sm border-0 w-40 rounded-full bg-accent font-normal hover:bg-primary text-primary hover:text-secondary transition ease-in-out duration-500 transform hover:scale-105 px-10 mt-4 pr-10 relative">
<span class="absolute left-6">Suscribete</span>
<span class="material-symbols-outlined absolute right-6">
add_circle
</span>
</button>
</div>
</div>
{/each}

AxiosError: Request failed with status code 403

I tried using this api-key provided by RapidAPI for my code. I made sure that the API key entered is correct. I was previously using the .env file,'X-RapidAPI-Host': process.env.COIN_RANKING_HOST, for both the api host and api key but to make sure that the error is not caused by the .env file not loading, I entered both directly. This is my code:
import Header from '../components/Header'
import PortfolioChart from '../components/PortfolioChart'
import BuyTokens from '../components/BuyTokens'
import Notice from '../components/Notice'
import Asset from '../components/Asset'
import { BiDotsHorizontalRounded } from 'react-icons/bi'
import { AiOutlinePlus } from 'react-icons/ai'
import axios from 'axios'
const styles = {
wrapper: 'w-screen h-screen flex flex-col',
mainContainer: 'w-2/3 h-full m-auto flex mt-16',
leftMain: 'flex flex-col w-3/4 h-full p-6 overflow-y-scroll',
portfolioAmountContainer: 'flex flex-col ',
portfolioAmount: 'text-white text-4xl',
portfolioPercent: 'text-white font-bold text-sm',
pastHour: 'text-gray-400',
chartContainer:
'text-5xl flex justify-center w-full h-1/3 text-white mt-11 mb-11',
buyingPowerContainer:
'w-full border-t mb-24 border-b h-16 border-[#30363b] flex justify-between items-center p-4',
buyingPowerTitle: 'text-white font-bolder text-lg',
buyingPowerAmount: 'text-white font-bolder text-xl',
notice: 'flex border border-[#30363b] mx-11 my-4 p-5 flex-col flex-1',
noticeContainer: 'flex-1',
noticeTitle: 'text-gray-500',
noticeMessage: 'text-white font-bold',
noticeCTA: 'font-bold text-green-500 cursor-pointer mt-5',
rightMain:
'flex flex-col flex-1 h-4/5 bg-[#1E2123] mt-6 rounded-lg overflow-y-scroll noScroll',
rightMainItem: 'flex items-center text-white p-5 border-b border-[#30363b]',
ItemTitle: 'flex-1 font-bold',
moreOptions: 'cursor-pointer text-xl',
}
export default function Home({coins}) {
console.log(coins)
return(
<div className={styles.wrapper}>
<Header />
<div className={styles.mainContainer}>
<div className={styles.leftMain}>
<div className={styles.portfolioAmountContainer}>
<div className={styles.portfolioAmount}>
23 SOLANA
</div>
<div className={styles.portfolioPercent}>
+0.0008(+0.57%)
<span className={styles.pastHour}>
Past Hour
</span>
</div>
</div>
<div>
<div className={styles.chartContainer}>
<PortfolioChart />
</div>
</div>
<div className={styles.buyingPowerContainer}>
<div className={styles.buyingPowerTitle}>Buying Power</div>
<div className={styles.buyingPowerAmount}>12 SOLANA</div>
</div>
<div className={styles.notice}>
<div className={styles.noticeContainer}>
<div className={styles.noticeTitle}>
Send Funds
</div>
<div className={styles.noticeMessage}>
Transfer your funds here.
</div>
<BuyTokens />
</div>
</div>
<Notice />
</div>
<div className={styles.rightMain}>
<div className={styles.rightMainItem}>
<div className={styles.ItemTitle}>
Crypto Currencies
</div>
<BiDotsHorizontalRounded className={styles.moreOptions} />
</div>
<Asset coin={"BTC"} price={0.89} />
<Asset coin={"SOL"} price={0.90} />
<Asset coin={"ETH"} price={-1} />
<Asset coin={"USDC"} price={2} />
<div className={styles.rightMain}>
<div className={styles.ItemTitle}>
Lists
</div>
<AiOutlinePlus className={styles.moreOptions} />
</div>
</div>
</div>
</div>
)
}
export const getStaticProps = async () => {
const options = {
method: 'GET',
url: 'https://coinranking1.p.rapidapi.com/coins',
params: {
referenceCurrencyUuid: 'yhjMzLPhuIDl',
timePeriod: '24h',
tiers: '1',
orderBy: 'marketCap',
orderDirection: 'desc',
limit: '50',
offset: '0',
},
headers: {
'X-RapidAPI-Host': 'coinranking1.p.rapidapi.com',
'X-RapidAPI-Key': '23734db4e2msha5580c4a7b981c0p1557d0jsn9c9dcf2b8505',
},
}
const res = await axios.request(options)
const coins = res.data.data.coins
return {
props: { coins },
}
}
The error showing in the terminal is this.The error was very lengthy and I couldn't post the entire error due to character limit. I have put up the initial two lines and the last two lines of the error though.
error - [AxiosError: Request failed with status code 403] {
code: 'ERR_BAD_REQUEST',
...
data: { message: 'You are not subscribed to this API.' }
},
page: '/'
}
I am unable to figure out why I am getting this error. Please help.
I am subscribed to RapidAPI.

Vue cli 3 props (parent to child) child never update after the variable in parent has changed

I tried to make a chat app using Vue CLI 3 and I have finished making a real-time chat room. Then, I tried to give a citing function to it which users can cite the message before and reply to it. So, I manage to pass the cited message to the child component by props. The cited message was NULL by default. After the user clicked some buttons, I expected the value of the "cited message" would change and the new value would be passed to the child through props (automatically updated). But, in fact, it didn't.
When I was browsing the internet, I did find several questions about updating the child component when props values change. So, I tried watch:, created(), update(), but none of them worked.
I once tried to directly add an element <p> in the child component and put {{cited_message}} in it to see what was inside the variable. Then, the Vue app crashed with a white blank page left (but the console didn't show any error).
For convenience, I think the problem is around:
<CreateMessage:name="name":cited_message="this.cited_message"#interface="handleFcAfterDateBack"/>
OR
props: ["name","cited_message"],
watch: { cited_message: function (newValue){ this.c_message = newValue; } },
You can ctrl+F search for the above codes to save your time.
Parent component:
<template>
<div class="container chat">
<h2 class="text-primary text-center">Real-time chat</h2>
<h5 class="text-secondary text-center">{{ name }}</h5>
<div class="card" style="min-height: 0.8vh">
<div class="card-body">
<p class="text-secondary nomessages" v-if="messages.length == 0">
[no messages yet!]
</p>
<div class="messages" v-chat-scroll="{ always: false, smooth: false }">
<div v-for="message in messages" :key="message.id">
<div v-if="equal_name(message)">
<div class="d-flex flex-row">
<div class="text-info">
[ {{ message.name }} ] : {{ message.message }}
</div>
<div class="btn-group dropright">
<a
class="btn btn-secondary btn-sm dropdown-toggle"
href="#"
role="button"
id="dropdownMenuLink"
data-toggle="dropdown"
aria-haspopup="true"
aria-expanded="false"
>
</a>
<div class="dropdown-menu" aria-labelledby="dropdownMenuLink">
<button
#click="get_cited_message(message)"
:key="message.id"
class="dropdown-item"
href="#"
>
Cite
</button>
</div>
</div>
<div class="text-secondary time">
<sub>{{ message.timestamp }}</sub>
</div>
</div>
<!--below is for cited message-->
<div v-if="message.cited_message" class="d-flex flex-row">
Cited : {{ message.cited_message }}
</div>
</div>
<div v-else>
<div class="d-flex flex-row-reverse">
<div class="text-info">
[ {{ message.name }} ] : {{ message.message }}
</div>
<div class="text-secondary time">
<sub>{{ message.timestamp }}</sub>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="card-action">
<CreateMessage
:name="name"
:cited_message="this.cited_message"
#interface="handleFcAfterDateBack"
/>
</div>
</div>
</div>
</template>
<script>
import CreateMessage from "#/components/CreateMessage";
import fb from "#/firebase/init.js";
import moment from "moment";
export default {
name: "Chat",
props: {
name: String,
},
components: {
CreateMessage,
},
methods: {
equal_name(message) {
if (message.name == this.name) {
return true;
} else {
return false;
}
},
get_cited_message(message) {
this.cited_message = message.message;
console.log(this.cited_message);
},
handleFcAfterDateBack(event) {
console.log("data after child handle: ", event);
},
},
data() {
return {
messages: [],
cited_message: null,
};
},
created() {
let ref = fb.collection("messages").orderBy("timestamp");
ref.onSnapshot((snapshot) => {
snapshot.docChanges().forEach((change) => {
change.type = "added";
if (change.type == "added") {
let doc = change.doc;
this.messages.push({
id: doc.id,
name: doc.data().name,
message: doc.data().message,
timestamp: moment(doc.data().timestamp).format(
"MMMM Do YYYY, h:mm:ss a"
),
cited_message: doc.data().cited_message,
});
}
});
});
},
};
</script>
<style>
.chat h2 {
font-size: 2.6em;
margin-bottom: 0px;
}
.chat h5 {
margin-top: 0px;
margin-bottom: 40px;
}
.chat span {
font-size: 1.2em;
}
.chat .time {
display: block;
font-size: 0.7em;
}
.messages {
max-height: 300px;
overflow: auto;
text-align: unset;
}
.d-flex div {
margin-left: 10px;
}
</style>
Child component:
<template>
<div class="container" style="margin-bottom: 30px">
<form #submit.prevent="createMessage()">
<div class="form-group">
<input
type="text"
name="message"
class="form-control"
placeholder="Enter your message"
v-model="newMessage"
/>
<p v-if="c_message" class="bg-secondary text-light">Cited: {{c_message}}</p>
<p class="text-danger" v-if="errorText">{{ errorText }}</p>
</div>
<button class="btn btn-primary" type="submit" name="action">
Submit
</button>
</form>
</div>
</template>
<script>
import fb from "#/firebase/init.js";
import moment from "moment";
export default {
name: "CreateMessage",
props: ["name","cited_message"],
watch: {
cited_message: function (newValue){
this.c_message = newValue;
}
},
data() {
return {
newMessage: "",
errorText: null,
c_message: null
};
},
methods: {
createMessage() {
if (this.newMessage) {
fb.collection("messages")
.add({
message: this.newMessage,
name: this.name,
timestamp: moment().format(),
cited_message: this.c_message
})
.then(function(docRef) {
console.log("Document written with ID: ", docRef.id);
})
.catch((err) => {
console.log(err);
});
this.newMessage = null;
this.errorText = null;
} else {
this.errorText = "Please enter a message!";
}
},
},
beforeMount(){
this.c_message = this.cited_message;
}
};
</script>
Side-note: In the parent component, I only made the dropdown menu for the messages on the left-hand side. If this thread solved, I would finish the right-hand side.
It is solved. I think the problem is that the child component didn't re-render when the variable in parent component updated. Only the parent component was re-rendered. So, the props' values in the child remained the initial values. In order to solve this, binding the element with v-bind:key can let the Vue app track the changes of the variable (like some kind of a reminder that reminds the app to follow the changes made on the key). When the variable(key) changes, the app will be noticed and the new value will be passed to the child.
E.g.
Original
<CreateMessage
:name="name"
:cited_message="this.cited_message"
#interface="handleFcAfterDateBack"
/>
Solved
<CreateMessage
:name="name"
:cited_message="this.cited_message"
#interface="handleFcAfterDateBack"
:key="this.cited_message"
/>
Even though the problem is solved, I don't know whether I understand the problem clearly. If I made any mistakes, please comment and let me know.

Bind class item in the loop

i want to bind my button only on the element that i added to the cart, it's working well when i'm not in a loop but in a loop anything happen. i'm not sure if it was the right way to add the index like that in order to bind only the item clicked, if i don't put the index every button on the loop are binded and that's not what i want in my case.
:loading="isLoading[index]"
here the vue :
<div class="container column is-9">
<div class="section">
<div class="columns is-multiline">
<div class="column is-3" v-for="(product, index) in computedProducts">
<div class="card">
<div class="card-image">
<figure class="image is-4by3">
<img src="" alt="Placeholder image">
</figure>
</div>
<div class="card-content">
<div class="content">
<div class="media-content">
<p class="title is-4">{{product.name}}</p>
<p class="subtitle is-6">Description</p>
<p>{{product.price}}</p>
</div>
</div>
<div class="content">
<b-button class="is-primary" #click="addToCart(product)" :loading="isLoading[index]"><i class="fas fa-shopping-cart"></i> Ajouter au panier</b-button>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
here the data :
data () {
return {
products : [],
isLoading: false,
}
},
here my add to cart method where i change the state of isLoading :
addToCart(product) {
this.isLoading = true
axios.post('cart/add-to-cart/', {
data: product,
}).then(r => {
this.isLoading = false
}).catch(e => {
this.isLoading = false
});
}
You can change your isLoading to an array of booleans, and your addToCart method to also have an index argument.
Data:
return {
// ...
isLoading: []
}
Methods:
addToCart(product, index) {
// ...
}
And on your button, also include index:
#click="addToCart(product, index)"
By changing isLoading to an empty array, I don't think isLoading[index] = true will be reactive since index on isLoading doesn't exist yet. So you would use Vue.set in your addToCart(product, index) such as:
this.$set(this.isLoading, index, true)
This will ensure that changes being made to isLoading will be reactive.
Hope this works for you.
add on data productsLoading: []
on add to cart click, add loop index to productsLoading.
this.productsLoading.push(index)
after http request done, remove index from productsLoading.
this.productsLoading.splice(this.productoading.indexOf(index), 1)
and check button with :loading=productsLoading.includes(index)
You can create another component only for product card,
for better option as show below
Kindly follow this steps.
place the content of card in another vue component as shown below.
<!-- Product.vue -->
<template>
<div class="card">
<div class="card-image">
<figure class="image is-4by3">
<img src="" alt="Placeholder image">
</figure>
</div>
<div class="card-content">
<div class="content">
<div class="media-content">
<p class="title is-4">{{product.name}}</p>
<p class="subtitle is-6">Description</p>
<p>{{product.price}}</p>
</div>
</div>
<div class="content">
<b-button class="is-primary" #click="addToCart(product)" :loading="isLoading"><i class="fas fa-shopping-cart"></i> Ajouter au panier</b-button>
</div>
</div>
</div>
</templete>
<script>
export default {
name: "Product",
data() {
return {
isLoading: false
}
},
props: {
product: {
type: Object,
required: true
}
},
methods: {
addToCart(product) {
this.isLoading = true
axios.post('cart/add-to-cart/', {
data: product,
}).then(r => {
this.isLoading = false
}).catch(e => {
this.isLoading = false
});
}
}
}
</script>
Change your component content as shown below.
<template>
<div class="container column is-9">
<div class="section">
<div class="columns is-multiline">
<div class="column is-3" v-for="(product, index) in computedProducts">
<product :product="product" />
</div>
</div>
</div>
</div>
</templete>
<script>
import Product from 'path to above component'
export default {
components: {
Product
}
}
</script>
so in the above method you can reuse the component in other components as well.
Happy coding :-)