简体   繁体   English

Vue.js如何在实例上定义方法

[英]Vue.js how to define methods on the instance

Hi I am trying to add json data to an element. 嗨,我正在尝试将json数据添加到元素。 I get the data via a jsonp call to an external API. 我通过对外部API的jsonp调用获取数据。 but somehow vue does not recognize that the variable is there. 但是以某种方式vue无法识别该变量存在。 Since the app is in laravel I read on laracasts forum that the data and methods properties should be defined in components , but that does not also solve my problem. 由于该应用程序位于laravel中,因此我在laracasts论坛上阅读了应在组件中定义数据和方法属性的信息,但这并不能解决我的问题。 I am using vue.js2 and laravel 5.4 I get the following error: 我正在使用vue.js2laravel 5.4我收到以下错误:

app.js: [Vue warn]: Property or method "names" is not defined on the instance but referenced during render. app.js:[Vue警告]:属性或方法“名称”未在实例上定义,但在渲染期间被引用。 Make sure to declare reactive data properties in the data option. 确保在data选项中声明反应性数据属性。

here is my code: 这是我的代码:

app.js 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>

You are trying to reference the names property in your parent template, but names is a property of your component. 您正在尝试在父模板中引用names属性,但是names是组件的属性。

However, there is no need for a component here. 但是,这里不需要组件。 Obviously you could use a component, but in that case you would need to move the template that references names down into the component. 显然,您可以使用组件,但是在这种情况下,您需要将引用names的模板向下移动到组件中。 Instead, here I am removing 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()
  }
});

And your template 还有你的模板

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

I found out what was going wrong. 我发现出了什么问题。 I should have wrapped the data, methods, and mounted properties into export default {}. 我应该将数据,方法和装入的属性包装到导出默认{}中。 This way it works fine now. 这样,它现在可以正常工作了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM