事件函数内的数据对象不起作用并导致未定义

编程入门 行业动态 更新时间:2024-10-11 21:32:10
本文介绍了事件函数内的数据对象不起作用并导致未定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

当我将对象数据放入事件时,我有一个未定义的值.

这是我的代码:

data(){返回 {事件来源:[],我的 ID:1}},方法:{我的方法(){this.eventSources = [{事件(开始,结束,时区,回调){警报(this.myId);axios.get(`/Something?id=${this.myId}`).then(response=>{回调(响应数据);}).catch(error=>{console.log(error);});}}]}}

我的警报结果为 undefined 但是当我将警报置于 this.eventSources = [{...]] 上方时,警报的值为 1

希望有人能帮助我.

解决方案

问题在于 events() 中的 this 实际上并不是你的 Vue 实例.您可以通过将 events 声明为 箭头功能:

this.eventSources = [{事件:(开始,结束,时区,回调)=>{警报(this.myId);}}]

new Vue({el: '#app',数据() {返回 {事件来源:[],我的 ID:1};},方法: {我的方法(){this.eventSources = [{事件:(开始,结束,时区,回调)=>{警报(this.myId);}}]this.eventSources[0].events(0, 1, 'UTC', data => console.log(data))}}})

<script src="https://unpkg/vue@2.5.16"></script><div id="应用程序"><button @click="myMethod">点击</button>

I'm having an undefined value when I put my object data inside the event.

Here are my codes:

data(){
    return {
       eventSources: [],
       myId: 1
    }
},
methods:{
   myMethod(){
     this.eventSources = [{
          events(start,end,timezone,callback){
              alert(this.myId); 
              axios.get(`/Something?id=${this.myId}`).then(response=>{
                  callback(response.data);
              }).catch(error=>{console.log(error);});
          }
     }]
   }
}

My alert is resulted to undefined but when I put my alert above the this.eventSources = [{...]] the alert has a value of 1

I hope somebody helps me.

解决方案

The problem is this inside events() is not actually your Vue instance. You can fix the context by declaring events as an arrow-function:

this.eventSources = [{
  events: (start,end,timezone,callback) => {
    alert(this.myId);
  }
}]

new Vue({
  el: '#app',
  data() {
    return {
      eventSources: [],
      myId: 1
    };
  },
  methods: {
    myMethod() {
      this.eventSources = [{
        events: (start,end,timezone,callback) => {
          alert(this.myId);
        }
      }]

      this.eventSources[0].events(0, 1, 'UTC', data => console.log(data))
    }
  }
})

<script src="https://unpkg/vue@2.5.16"></script>

<div id="app">
  <button @click="myMethod">Click</button>
</div>

这篇关于事件函数内的数据对象不起作用并导致未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

更多推荐

[db:关键词]

本文发布于:2023-04-26 23:21:50,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1144902.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:函数   不起作用   对象   事件   未定义

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!