Defining methods within Vue.js instances: A comprehensive guide

Hey there! I'm working on adding JSON data to an element by making a JSONP call to an external API. It seems that Vue is not recognizing the variable properly, even after following advice from the Laracasts forum about defining data and methods in components. My setup involves using vue.js2 with Laravel 5.4.

The error message I receive is: [Vue warn]: Property or method "names" is not defined on the instance but referenced during render. Make sure to declare reactive data properties in the data option.

Below is my code:

app.js

Vue.component('search', 
 { 
    template: '<div class="panel-heading" ></div>',
      data: function(){
        return {
           names: []
        }
    },

    methods:  {
         getData: function(){
             var self = this;
              // GET request
           this.$http.jsonp(url,
           {
            jsonpCallback: "JSON_CALLBACK"
            })
           .then(
               response=>{
                  this.names = response.body
               })}      

      }
 });

const app = new Vue({
    el: '#search'
});

blade template

<div id='search'>
<search v-for='name in names'>
@{{name.label.eng}}
</search>
</div>

Answer №1

When attempting to access the names property within your parent template, it appears that names is actually a property of your component.

It seems unnecessary to use a component in this scenario. While it is possible to utilize a component, doing so would require transferring the template referencing names into the component. For now, I have eliminated the need for the component.

const app = new Vue({
  el: '#search',
  data:{
    names: []
  },
  methods:  {
    getData(){
      this.$http.jsonp(url, {jsonpCallback: "JSON_CALLBACK"})
       .then(response => this.names = response.body)
    }           
  },
  mounted(){
    this.getData()
  }
});

Incorporate the following template:

<div id='search'>
  <div v-for='name in names' class="panel-heading">
    @{{name.label.eng}}
  </div>
</div>

Answer №2

After some investigation, I discovered the issue at hand. It turns out that enclosing the data, methods, and mounted properties within export default {} was the solution. Thankfully, everything is now functioning properly.

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

Using CSS selectors globally within Laravel Dusk testing

For my project, I am utilizing Laravel Dusk in order to create Selenium tests. One of the classes within my testing directory is called PrivilegeLevelsTest and resides in the tests\Browser folder. Within this class, I am employing a variety of intric ...

Identify the changed field using Javascript

In my MVC application, I have a form with multiple fields that I am monitoring for changes using JavaScript. The code snippet below keeps track of any changes made in the form: var _changesMade = false; // Flag the model as changed when any other fie ...

Issue with Vue Multiselect not showing options

I'm currently implementing Vue Multiselect V2 in my Laravel 5.3 project using the example provided at In my app.js file, I have the following setup: Vue.component('multiselect', require('./components/Multiselect.vue')); var vm = ...

Using Laravel to dynamically display content in a tabbed interface

I'm confident that I have the structure set up correctly, but for some reason, the tab links on the page are not causing a refresh. It seems like changing the URI and Tag parameter does make the page load to an extent. However, the links themselves do ...

Warning: The update depth in Nextjs has surpassed the maximum limit

I am currently developing a React Header component with a dropdown menu feature that can be toggled. Upon loading the page, I encountered the following error: next-dev.js?3515:20 Warning: Maximum update depth exceeded. This issue may arise when a compone ...

How can you stop VueUse useStorage from filling localStorage again after clearing it?

Using Vue 3 in combination with VueUse's useStorage to sync reactive state with localStorage has presented a challenge for me. Whenever I programmatically clear localStorage during user logout processes, it seems to automatically refill with previous ...

I'm having trouble with my carousel. I suspect it's the "link-rel" in the head tag that's causing the issue

Having trouble with my carousel - it's not navigating properly. When I check the console, it shows: Failed to find a valid digest in the 'integrity' attribute for resource '' with computed SHA-256 integrity 'YLGeXaa ...

What is the best way to determine the number of characters that will fit within the width of the document?

I am looking to create a JavaScript function using jQuery that can determine the number of characters that will fit in a single line within the browser window. While I am currently utilizing a monospace font for simplicity's sake, I would like to adap ...

Using TypeScript to Trigger Events in Three.js

After recently diving into Typescript, I encountered an issue when using EventEmitter from the ThreeJS library. Whenever I attempt to trigger an event: const event: THREE.EventDispatcher = new THREE.EventDispatcher(); event.addEventListener('test&apo ...

The scrollbar within the Iframe stops before reaching the end of the content. Is there a method to adjust the scrollbar height to match the height

Is there anyone who can assist me with this issue? A large webpage is getting cut off by about 70% near the end of the scroll bar. Here is the code snippet in question: </div> <div id="divCustomDataPreview" title="Custom Form Preview" styl ...

Why is it necessary to implement AJAX cross-domain security measures?

It's puzzling to me why client side AJAX is restricted from making calls across domains, especially when it's so easy to create a server side proxy for fetching data. I'm not interested in speculation; I want to know the reasoning behind thi ...

Capturing information from a modifiable table using Javascript

Creating an HTML Editable table with the property CONTENTEDITABLE, each TD has a unique ID (even though it's a long process and I only have basic JS knowledge) to keep track of the information inside. The table is wrapped by a form. At the end of the ...

Create a new class in the body tag using Javascript

If the operating system is MAC, I set a variable and then based on a condition, I want to add a new class in the body tag. Check out my code snippet: <script type="text/javascript" language="javascript"> var mac = 0; if(navigator.userAgent.index ...

What steps should be followed to upgrade node.js from version 5.9.1 to 6.14.0 in a secure manner

Our current node version is 5.9.1 and we are looking to transition to a newer version that supports ES6. Specifically, I am aiming to upgrade to at least version 6.14.0, which is known to support almost all of the ES6 features. However, I must admit that ...

Enhance your security with Ember-simple-auth when using ember-cli-simple-auth-token

Currently, I am in the process of utilizing ember-simple-auth alongside ember-cli-simple-auth-token: "ember-cli-simple-auth-token": "^0.7.3", "ember-simple-auth": "1.0.1" Below are my configurations: ENV['simple-auth-token'] = { authoriz ...

What are some steps I can take to diagnose why my Express server is not receiving POST requests from my HTML form?

Struggling with an unexpected issue on my website where the form submission is not triggering the POST request to my Express server. I've set up a MongoDB database and created a HTML form to store user data, but something seems to be amiss. HTML: & ...

Adjusting canvas/webgl dimensions to match screen width and height

Hey, I'm currently working on resizing my canvas/webgl to fit the window's height and width at 100%. It works initially, but when I resize the window from small to large, it doesn't scale/fit properly anymore and remains small. Any suggestio ...

Redirecting in Next.js without the use of a React component on the page

I need to redirect a page using HTTP programmatically only. The following code achieves this: export const getServerSideProps: GetServerSideProps = async (context) => { return { redirect: { destination: '/', permanent: false, ...

Using JavaScript to access array INDEX values sequentially

I have created a Stacked Bar chart using the Js library dhtmlx, and here is the generated output: The JSON data is structured as follows: var data = [ { "allocated":"20", "unallocated":"2", "day":"01/01/2014" }, { "allocated":"12", "unallocated": ...

Struggling to retrieve the data from my table (getElementById function is malfunctioning)

I am attempting to retrieve a line from a dynamic table once the "reserve" button is clicked (or the line itself is clicked if that is important), but the 'getElementById' function is not returning anything (I want to display them in an input). H ...