Using Boolean as a prop in Vue.js

Creating a Vue form to ask a question involves making a component:

<template>
  <div class="flex flex-col items-center justify-center gap-2">
    <div class="flex w-[80%] items-center justify-center gap-2 rounded-3xl p-2">
      <textarea
        class="w-full"
        :placeholder="ansPlaceholder"
        :value="modelValue"
        @input="$emit('update:modelValue', $event.target.value)"
      ></textarea>
      <input
        type="checkbox"
        :value="checkboxValue"
        name="isTrue"
        @change="$emit('update:checkboxValue', $event.target.value)"
      />
    </div>
  </div>
</template>

<script setup>
// eslint-disable-next-line no-unused-vars
const props = defineProps({
  ansPlaceholder: {
    type: String,
    default: 'default'
  },
  modelValue: {
    type: String
  },
  checkboxValue: {
    type: Boolean
  }
})

defineEmits(['update:modelValue', 'update:checkboxValue'])
// eslint-disable-next-line no-unused-vars
</script>

<style scoped></style>

Then, there is the main component:

<template>
  <div
    name="form container"
    class="mx-auto flex w-[70%] flex-col items-center justify-center rounded-3xl border-2 border-black"
  >
    <div name="question" class="flex w-[80%] flex-col items-center justify-center gap-3 p-3">
      <p class="text-2xl font-semibold">Question</p>
      <textarea class="w-[80%]" placeholder="Add a question" v-model="question"></textarea>
    </div>
    <div name="border" class="mx-auto w-[50%] rounded-3xl border-2 border-gray-400"></div>
    <div name="answers" class="flex w-[80%] flex-col gap-2 p-3">
      <FormAnswer
        ansPlaceholder="Answer A"
        v-model:modelValue="answers[0]"
        v-model:checkboxValue="isTrue[0]"
      ></FormAnswer>
      <FormAnswer
        ansPlaceholder="Answer B"
        v-model:modelValue="answers[1]"
        v-model:checkboxValue="isTrue[1]"
      ></FormAnswer>
      <!-- <FormAnswer ansPlaceholder="Answer C"></FormAnswer>
      <FormAnswer ansPlaceholder="Answer D"></FormAnswer>
      <FormAnswer ansPlaceholder="Answer E"></FormAnswer> -->

      <select>
        <option value="">Database 1</option>
        <option value="">Database 2</option>
      </select>
      <button
        class="mx-auto mt-2 w-fit rounded-3xl border-2 border-black p-3 text-xl font-semibold transition-all duration-500 hover:scale-105 hover:bg-black hover:text-white"
        @click="getFormData()"
      >
        Submit question
      </button>
    </div>
  </div>
</template>

<script setup>
import FormAnswer from '../AdminDashboardCmp/FormAnswer.vue'
import { ref } from 'vue'
const question = ref('')
const answers = []
const isTrue = ref('')

function getFormData() {
  console.log(answers)
}
</script>

<style scoped></style

The objective is to log the answer as an object { answer:'lorem ipsum', isTrue: false } and if the checkbox is clicked, { answer:'lorem ipsum', isTrue: true}. However, passing boolean as a prop seems to be an issue.

   <textarea
        class="w-full"
        :placeholder="ansPlaceholder"
        :value="modelValue"
        @input="$emit('update:modelValue', $event.target.value)"
      ></textarea>

Followed by

const props = defineProps({
  ansPlaceholder: {
    type: String,
    default: 'default'
  },
  modelValue: {
    type: String
  },

defineEmits(['update:modelValue', 'update:checkboxValue'])

and then

   <FormAnswer
        ansPlaceholder="Answer A"
        v-model:modelValue="answers[0]"
        v-model:checkboxValue="isTrue[0]"
      ></FormAnswer>

While it worked for passing text, encountering issues with passing boolean. How can this be resolved?

Answer №1

When your isTrue value is set as a type string, the elements isTrue[0] and isTrue[1] are not boolean values. To rectify this, consider initializing it as an array instead.

Replace const isTrue = ref('') with

const isTrue = reactive([true, false])

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Navigating through div elements using arrow keys in Vue

Trying to navigate through div elements using arrow keys is proving to be a challenge for me. I have successfully achieved it in JavaScript, but I am facing difficulties doing it the "vue way". Although there should be no differences, it simply does not wo ...

What is the best way to modify an object within a pure function in JavaScript?

Currently, I am exploring different strategies to ensure that a function remains pure while depending on object updates. Would creating a deep copy be the only solution? I understand that questions regarding object copying are quite common here. However, ...

Assign a specific value to each object

Receiving data from the backend in a straightforward manner: this.archiveService.getRooms(team).subscribe( res => { this.form = res; this.form.forEach(el => { el.reservation.slice(-6).match(/.{1,2}/g).join('/'); }); }, ...

Unslider: Ensure images stay centered even on smaller screen resolutions

Utilizing Unslider in a recent project from . Managed to align the slider halfway, but facing an issue with off-center slides on resolutions of 1920px and lower. The image width is 3940px. Attempted to implement the code snippet from this answer like so: ...

using a ternary operator within the map function

Currently, I'm developing a web application that allows users to view a list of items and mark certain items as favorites. The favorites are stored in an array of IDs assigned to a prop (this.props.favorites). To ensure there are no duplicate entries, ...

Show where the image should be placed according to the coordinates of the mouse click

My project begins with a blank canvas, prompting the user to click anywhere on the page to reveal an image. My goal is to show an image at the exact location where the user clicks. Although I can successfully trigger an image to appear in the corner of the ...

When using Javascript to append content to the body, it may not be displayed as HTML on

My current project involves creating an HTML document through JavaScript templates. In the code snippet below, I have a const button which serves as my template. By using the replace method, I am able to update the content within the button template from c ...

The stylesheet_pack_tag seems to be malfunctioning as it is not producing any output, despite the fact that the CSS file exists

After a Rails update, we encountered an issue with the stylesheet_pack_tag in our VueJS client application. Even though Webpacker successfully generates the CSS file in the /public/packs folder along with other files such as JS, the stylesheet_pack_tag s ...

EJS failing to render HTML within script tags

Here is some code that I'm working with: <% // accessing content from a cdn api cloudinary.api.resources( { type: 'upload', prefix: '' }, (error, result) => { const assets = result.r ...

modification of class into hooks, receiving error message 'then' property is not found in type '(dispatch: any) => Promise<void>'

As a newcomer to React hooks, I have been converting code from class components to hooks. However, I am encountering an error message when trying to use 'then' in hooks that says 'Property 'then' does not exist on type '(dispa ...

Floating Action Button is not properly attached to its parent container

When developing my React Js app, I decided to utilize the impressive libraries of Material UI v4. One particular component I customized is a Floating Action Button (FAB). The FAB component, illustrated as the red box in the image below, needs to remain p ...

How to effectively use the LIKE statement in mysql with node.js

app.post('/like/:level/:name', function(req, res){ connection.query("SELECT * from books where " + req.params.level + " like '%" + req.params.name + "'%", function(err, rows, fields) { if (!err){ var row = rows; res.send(row); console.l ...

What method can I use in webpage coding to achieve this special highlight effect, and what is the official term for it?

Need help figuring out how to make an icon change from blue to white when selected. I've searched through Bootstrap, CSS, and HTML, but haven't found the solution yet. Any suggestions would be appreciated! https://i.stack.imgur.com/RK1PD.png ...

Leveraging promises in conjunction with mongoose operations

I'm new to using promises in conjunction with mongoose query functions such as find() and findById(). While everything seems to be functioning correctly, I am unsure if the way I am chaining then is the proper approach. The goal of utilizing promises ...

[Vue Alert]: Attempted to access property "0" during rendering, but it has not been defined on the current instance

I'm fairly new to working with Vue3, currently in the process of creating a small Onboarding portal using Vue. I've implemented a global state within my "App.vue" file called const progressStage = ref(0), which dictates which components are rende ...

Vue template compilation issue: 'undefined' properties cannot be read (referencing '_c')

Currently, I am in the process of integrating a customized tool into an existing Laravel application by utilizing Laravel Nova for the administrative panel. However, the automatically generated tool created with "php artisan nova:tool vendor/name" does not ...

What is the general consensus on combining SWR with Redux - is it considered a best practice?

I am currently incorporating both SWR and Redux into my code. Here is how I'm using them together: const vehiclesStates = useSelector(({ vehiclesStates: state }) => state); // REDUX const response = useFetch("/vehicles/states") // SWR con ...

Hey there everyone, I was wondering how to send both single and multiple values to a database using JavaScript and JSON endpoints with a Spring Web API

{ "id": 178, "stockin_date": "2022-11-15T08:18:54.252+00:00", "effective_date": null, "expired_date": null, "create_date": null, "update_date&q ...

Alert from Webpack regarding a critical dependency in the view.js file of the Express library located in the node_modules directory: an expression is being used

Currently, I'm in the process of working on my inaugural full stack application (a simplistic notepad app) and while bundling webpack, I've encountered an issue that is a cause for concern: WARNING in ./node_modules/express/lib/view.js 81:13-2 ...

Using AngularJS to invoke the ng-required directive and trigger a function

Is it possible to make the required value dependent on a function? Something similar to this? I need to achieve this in order to dynamically change the required attribute for form inputs... HTML: Name: <input type="text" ng-model="user.name" ng-r ...