How to pass a prop from Nuxt.js to a component's inner element

I've created a basic component:

<template>
    <div id="search__index_search-form">
        <input :bar-id="barId" @keyup.enter="findBars()" type="text" :value="keyword" @input="updateKeyword"
               placeholder="Search for a bar">
        <button @click="findBars()">Search!</button>
        {{barId}}
    </div>
</template>

<script>
    import {mapState} from "vuex";

    export default {
        computed: mapState({
            keyword: state => state.search.keyword
        }),
        data: function () {
            return {barId: "all"};
        },
        methods: {
            updateKeyword(e) {
                this.$store.commit("setSearchKeyword", e.target.value);
            },
            findBars() {
                this.$store.dispatch("findBars");
            }
        }
    };
</script>

I am using it on a nuxt page like so:

<template>
    <custombar v-bind:barId="500"/>
</template>
<script>
    import customBar from "~/components/custom-bar.vue";

    export default {
        components: {
            'custombar': customBar
        }
    };
</script>

After rendering, I'm seeing:

<div id="search__index_search-form" barid="500"><input shop-id="all" type="text" placeholder="Search for a bar"><button>Search!</button>
      all
</div>

Why is the barId attribute bound to the "div.search__index_search-form" instead of the input? And how come {{barId}} displays "all" (default value), and not "500"?

Answer №1

fooId is being displayed on div#search__index_search-form because you forgot to define fooId as a property of the component. By default, Vue will display undefined properties on the root element of the component.

To fix this issue, you need to declare fooId as a property in your component.

 export default {
    props: {
      fooId: {type: String, default: "all"}
    },
    computed: mapState({
        keyword: state => state.search.keyword
    }),
    methods: {
        updateKeyword(e) {
            this.$store.commit("setSearchKeyword", e.target.value);
        },
        findProducts() {
            this.$store.dispatch("findFoos");
        }
    }
};

I'm not sure what exactly you are trying to achieve with this code.

<input :foo-id="fooId" ... >

This part of the code doesn't appear to have a clear purpose.

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

Maintaining TextBox State in ASP.Net Through Postbacks

Can anyone help me figure out how to maintain the control state that has been modified in Javascript? I am working with two TextBoxes, one DropDownList, and a button (all Runat=Server) in C# ASP.net 2010 Express. The first textbox accepts any user in ...

How can I retrieve the line number of a code during runtime in JavaScript?

Is there a way to add a console.log statement that would indicate the line number it is on in JavaScript? For example: console.log ('Line:', [code to get the line]). The output in the console would be Line: [line number], helping me identify wher ...

There seems to be an issue with Material UI Autocomplete not responding to the onChange value

I am currently developing a project using reactjs and incorporating material ui to create components. One specific component I have utilized is the Autocomplete within a form for event creation in my project. I am encountering an issue where I want the sta ...

What changes should I make to my save function in order to handle both saving and editing user information seamlessly?

My goal for the save function is to achieve two tasks: 1. Save user in table - Completed 2. Update user in table - In progress Save function snippet: var buildUser = function () { $('#save').click(function () { var newUser = {}; ...

Customizing object joining rules in JavaScript arrays

My array consists of different colored items with their respective types and amounts [ { color: 'blue', type: '+', amount: '1' }, { color: 'blue', type: '-', amount: '1' }, { color: 'blu ...

What methods are available to gradually increase a counter until it reaches a specific number by a designated date?

I have a unique idea for my website - I want to create a special counter that gradually increases to a specific number, but does so over the course of an entire year. Imagine starting at 0 and aiming to reach 35340340 after exactly one year has passed. It ...

Is Webpack CLI causing issues when trying to run it on a .ts file without giving any error

I am facing an issue with my webpack.config.js file that has a default entrypoint specified. Here is the snippet of the configuration: module.exports = { entry: { main: path.resolve('./src/main.ts'), }, module: { rules: [ { ...

Do watches operate asynchronously?

I am monitoring the status of a variable called radioStatus within a Vue instance: watch: { radioStatus: function(val) { if (!this.discovery) { $.ajax({ url: '/switch/api/radio/' + (val ? 'on' : 'off') }) ...

Save the value of a webpage element into a variable and utilize it across multiple JavaScript files in TestCafe

We are working in the insurance domain and have a specific scenario that we want to achieve using TestCafe: 1st step: Login into the application 2nd step: Create a claim and store the claim number in a global variable 3rd step: Use the globally declared c ...

JavaScript Application - Problem with Universal Windows Script

I recently built a website utilizing material design lite for the aesthetics: Here are the scripts included: <script src="./mdl/material.min.js"></script> <script src="Scripts/angular.min.js"></script> The necessary .css fi ...

Effortless JavaScript function for retrieving the chosen value from a dropdown menu/select element

I've figured out how to retrieve the value or text of a selected item in a dropdown menu: document.getElementById('selNames').options[document.getElementById('selNames').selectedIndex].value In order to simplify this code, I&apos ...

Angular 13.0 version is experiencing issues when trying to run the "ng serve" command

After installing the npm module, I encountered a problem while using node.js version 14.17.6. I am a beginner in Angular and struggling to find a solution due to not using the latest Angular CLI version. Any help would be greatly appreciated. Thank you in ...

Aligning text vertically to the top with material UI and the TextField component

Seeking guidance on adjusting vertical alignment of text in <TextField /> const styles = theme => ({ height: { height: '20rem', }, }); class Foo extends React.component { ... <TextField InputProps={{ classes: ...

Toggle button to create a fade in/out effect

Below is the HTML code snippet: <html> <head> <Script type = "text/javascript" src = "CprMdlrSrch.js"></Script> <link type="text/css"rel="stylesheet"href="CprMdlrSrch.css"/> </head> <body> <div id=" ...

I'm experiencing an issue with Gravity Forms validating hidden fields, is there a solution for this problem?

On my webpage, there are four fields labeled A, B, C, and D. Each field has its own set of conditional logic that determines whether it should be visible or hidden. Let's say a user lands on this page and only field B is displayed while the others are ...

Strategies for avoiding interruption of the dragenter event while dragging over a nested element

I'm currently developing a personalized drop zone feature. Below is the HTML code snippet: <template>   <div class="dropzone"     @drop.prevent="dropFileHandler"     @dragover.prevent="dragOverHandler" ...

Information backed by the HTML5 Local Storage feature

Is it possible to use a Local Storage object to store another Local Storage object? Thank you in advance. ...

Adding colors dynamically upon page reload with javascript and jQuery

I have created an array of colors and am attempting to use colors.forEach inside the ready function to call addBox for each color in the array. My goal is to ensure that all the colors are added when the page is reloaded. Please let me know if you require ...

Guide to merging two endpoints in express.js to create a single endpoint

I currently have 2 existing endpoints named /balance and /transactions. What is the most effective approach to create a new endpoint called /balance-and-transactions without having to refactor the existing code? For example: a('/balance', () =&g ...

Using the input type 'number' will result in null values instead of characters

My goal is to validate a number input field using Angular2: <input type="number" class="form-control" name="foo" id="foo" [min]="0" [max]="42" [(ngModel)]="foo" formControlName="foo"> In Chrome, everything works perfectly because it ignores ...