After triggering a click event
, I am attempting to choose a message from a json
file. However, I am encountering an issue where the first click does not seem to select anything. Upon the second click, the selected messages are duplicated, and this pattern continues with each subsequent click.
I believe the problem lies in the following code snippet:
import SelectedItem from "../Interfaces/SelectedItem";
const selectedMessage = ref<MessageInterface | null>(null);
const selectMessage = (message: any) => {
selectedMessage.value = message;
SelectedItem(selectedMessage);
};
The structure of the SelectedItem module is as follows:
import { watch, Ref } from "vue";
export default function SelectedItem<Type>(selectedValue: Ref<Type>): Type {
watch(selectedValue, (newVal) => {
chooseItem(newVal);
});
function chooseItem(item: Type) {
if (item) {
selectedValue.value = item;
console.log(selectedValue.value);
}
}
return selectedValue.value;
}
The rationale behind separating the SelectedItem
function is to avoid repetition of logic and code across multiple files.
Here's a segment of the code:
<template>
<div>
<select v-model="selectedMessage">
<option value="">Select target number</option>
<option
v-for="(message, index) in SMSMessages"
:key="index"
:value="message.targetNumber"
>
{{ message.targetNumber }}
</option>
</select>
<p>Selected: {{ selectedMessage }}</p>
</div>
</template>
<script setup lang="ts">
import SMSMessages from "../data/sms-messages.json";
import { ref } from "vue";
import SelectedItem from '../Interfaces/SelectedItem'
const selectedMessage = ref<string>("");
selectedMessage.value = SelectedItem(selectedMessage);
</script>
Full code can be seen below:
<template>
<div>
<ul>
<li
v-for="(message, index) in SMSMessages"
:key="index"
@click="selectMessage(message)"
>
<p>Body: {{ message.body }}</p>
<p>Origin Number: {{ message.originNumber }}</p>
<p>Target Number: {{ message.targetNumber }}</p>
<p>Direction: {{ message.direction }}</p>
<p>Message Date: {{ message.messageDt }}</p>
</li>
</ul>
</div>
</template>
<script setup lang="ts">
import SMSMessages from "../data/sms-messages.json";
import MessageInterface from "../Interfaces/MessageInterface";
import { ref } from "vue";
import SelectedItem from "../Interfaces/SelectedItem";
const selectedMessage = ref<MessageInterface | null>(null);
const selectMessage = (message: any) => {
selectedMessage.value = message;
SelectedItem(selectedMessage);
};
</script>