sending properties into a vue2 component

I have a simple Vue component that I am trying to pass information into using props. The HTML code for this looks like:

<myapp v-bind:source-key="some_key" v-bind:destination-key="some_other_key"></myapp>

Here is the component code:

<template>
    <div class="container">
        <div class="row justify-content-center">
            <div class="col-md-8">
                <div class="card card-default">
                    <div class="card-header">Example Component</div>

                    <div class="card-body">
                        This is an example component.
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
    export default {
        props: ['sourceKey', 'destinationKey'],
        mounted() {
            this.$http.get('/map/' + this.sourceKey + '/' + this.destinationKey)
                .then(function (response) {
                    console.dir(response)
                })
                .catch(function (error) {
                    console.dir(error);
                });
            console.log('Got here')
        }
    }
</script>

When trying to set the props sourceKey to some_key and destinationKey to some_other_key, I am encountering errors:

[Vue warn]: Property or method "some_key" is not defined on the instance but referenced during render. Make sure that this property is reactive, either in the data option, or for class-based components, by initializing the property. See: https://v2.vuejs.org/v2/guide/reactivity.html#Declaring-Reactive-Properties.

It seems like the expected value is being treated as the key. Additionally, errors indicate that the sourceKey variable was not defined:

[Vue warn]: Error in mounted hook: "ReferenceError: sourceKey is not defined"

Where should I define the props if not in the props block?

Answer №1

Right here:

this.$http.get('/map/' + sourceKey + '/' + destinationKey)

Within the <script> tags, be sure to reference this.sourceKey and this.destinationKey to indicate that you are targeting properties of the Vue instance specifically, rather than variables defined elsewhere. Remember that you can omit this. in templates only.

Regarding your initial error, double check that some_key and some_other_key are indeed variables defined within your Vue instance, whether in the data() { ... } section, computed properties, or any other relevant areas, as indicated by the error message.

Answer №2

Within the parent's template:

<myapp v-bind:source-key="some_key" v-bind:destination-key="some_other_key"></myapp>

An error is triggered:

[Vue warn]: The property or method "some_key" is not defined within the instance but is referenced during rendering. It is crucial for this property to be reactive, either within the data option, or for class-based components, by initializing the property. Please refer to: https://v2.vuejs.org/v2/guide/reactivity.html#Declaring-Reactive-Properties.

This occurs because the parent does not have some_key in its data() section.

Within the child component:

[Vue warn]: Error in mounted hook: "ReferenceError: sourceKey is not defined"

An error is triggered due to the fact that inside the Vue instance functions, props must be referenced using this.

View a demonstration rectifying both issues below.

Vue.component('myapp', {
  template: "#myAppTemplate",
  props: ['sourceKey', 'destinationKey'],
  mounted() {
    this.$http.get('/map/' + this.sourceKey + '/' + this.destinationKey) // this fixes "ReferenceError: sourceKey is not defined"
      .then(function(response) {
        console.dir(response)
      })
      .catch(function(error) {
        console.dir(error);
      });
    console.log('execution successful')
  }
})

new Vue({
  el: '#app',
  data: {
    some_key: 'aaa',       // this fixes [Vue warn]: Property or method "some_key" is not defined
    some_other_key: 'bbb'  // this fixes [Vue warn]: Property or method "some_other_key" is not defined
  }
});
<script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="091e1f0f4709081e0208190a0c392c231924">[email protected]</a>/dist/vue.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="691f1c1c542b1c0a061c1b0a0c29151c1a">[email protected]</a>"></script>

<div id="app">
  <myapp v-bind:source-key="some_key" v-bind:destination-key="some_other_key"></myapp>
</div>

<template id="myAppTemplate">
    <div class="container">
        <div class="row justify-content-center">
            <div class="col-md-8">
                <div class="card card-default">
                    <div class="card-header">Example Component</div>

                    <div class="card-body">
                        I'm an example component.
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

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

Modify the form's action attribute when submitted

I am trying to create a form with multiple buttons that will change the action and target properties when a specific button is clicked. Below is my code snippet: <div id="root"> <form :action="form.action" ref="form" :target="form.target"&g ...

npm update fails to update specific packages

After React was updated to version 0.15 to address the issue of excessive generation of tags, I made the decision to update my project.</p> <p>However, when I ran the command <code>npm update, it only updated to version 0.14.8. Running ...

Loading 3D models in Three.js from the cache

Every time my page reloads, the loader loads objects from the URL instead of cache. Is there a way to check if the resource is in cache and load it directly? Appreciate your help! ...

I'm having trouble finding the solution to setting a token in my request header

I have been following a tutorial in a book to build the authentication for my app. However, I am facing an issue where after logging in correctly, I am unable to set the token back into the request. The error message that I receive is: Failed to execute ...

"Maximizing the slider with jCarousel: A guide to enhancing your carousel experience

I recently added jcarousel to my website and things are looking good so far. Take a peek at how my site is currently set up: check it out! What I'm aiming for now is a feature where if a user clicks on an image to enlarge, it will open in a new tab ...

Is it common practice to provide a callback function as a parameter for an asynchronous function and then wrap it again?

app.js import test from "./asyncTest"; test().then((result)=>{ //handle my result }); asyncTest.js const test = async cb => { let data = await otherPromise(); let debounce = _.debounce(() => { fetch("https://jsonplaceholde ...

Creating a virtual field on an array item in VueJS

While developing with VueJS, I encountered an issue when trying to select an item from a list: Consider the following VueJS component: new Vue({ el: '#app', data: { list: [ { id: 1, title: 'My first Item&a ...

How can you delay the return of a function until after another asynchronous call has finished executing?

Currently, I am working on implementing route authentication in my project. To achieve this, I have decided to store the authenticated status in a context so that other React components can check whether a user is logged in or not. Below is the relevant co ...

Utilize the scrollIntoView method within a jQuery function

My current setup involves using JQuery's show and hide function. Essentially, when an image is clicked, it triggers the display of an information log. The issue I am facing is that this log opens at the top of the page, whereas I would like it to scro ...

Error Message: ElectronJS - Attempted to access the 'join' property of an undefined variable

I am currently working on developing a tray-based application. However, I am encountering an error that reads: Uncaught TypeError: Cannot read property 'join' of undefined Can anyone guide me on how to resolve this issue? This is the content ...

Using Webix in conjunction with Vue.js to make method calls

Is there a way to invoke the method storeNewOrder in the onAfterDrop event from the Webix component? Neither this.$emit.storeNewOrder() nor storeNewOrder() seem to be effective. export default { template:"<div></div>", pro ...

Leveraging Techniques within Computed Attributes using stored values in Vuex

I've been working with Vuex and I'm facing a challenge where I need to utilize methods within a computed property, similar to what I have set up in my actual project. However, I'm struggling to understand how to invoke the method and store t ...

XState: linking together multiple promises seamlessly without needing intermediate states

After reading the Invoking Multiple Services section, it seems that despite being able to invoke multiple promises, they appear to be triggered without waiting for the previous one to complete in my own tests. // ... invoke: [ { id: 'service1' ...

Filter the array while maintaining its current structure

I'm struggling to create an array filter that can handle exact and partial data within a nested array structure. The challenge is maintaining the integrity of the top-level structure while filtering based on data in the second layer. Here's an ex ...

Issues with Angular toggle sorting functionality not functioning as expected

$scope.searchObject = { from: 0, hydrate: false, size: 12, sort: 'timestamp:desc' }; $scope.sort = function(a) { var ascend = a + ':' + 'asc'; var descend = a + ':' + 'desc'; if ($scope.searc ...

Locating content inside a span element with tags and spacing in jquery

Within the span class of teamName, there are various tags including white-spacing, a sup tag, and a p tag: <span class="teamName"> Dr.<sup>J</sup> W Smith ...

Why is 'this.contains' not recognized as a function when I invoke it within another function?

While attempting to create a Graph and incorporating one method at a time, I encountered an issue. Specifically, after calling a.contains("cats"), I received the error '//TypeError: Cannot read property 'length' of undefined'. Could thi ...

Styling the sub-elements using CSS in JavaScript

Currently, I am dealing with two CSS classes: .dragbox and .removebutton. The .dragbox represents a div, while the .removebutton is a button nested within the div. On my page, there are multiple dynamically generated instances of .dragbox. I am seeking ...

Target specifically the onhover div element using JQuery and trigger the smooth sliding down effect with the SlideDown() function

Is it possible to create a unique JQuery slidedown() function that will only be applied to the div where the mouse is hovering? I have managed to make it work by giving each div a separate class, but when I name them all the same, it triggers the slide do ...

Executing ws.send from the controller in a Node.js environment

In my project, I am looking to send a websocket using express-ws from a different controller rather than through a route. In my server.js file, I have the following code: var SocketController = require('./routes/ws.routes'); var app = express(); ...