methods方法中forEach循环绑定事件无效
发布于 2年前 作者 p0301y 713 次浏览 来自 问答
粉丝福利 : 关注VUE中文社区公众号,回复视频领取粉丝福利
methods: {
          getContent: function (event) {
              var obj = {}
              obj.id = event.target.id
              obj.type = event.target.type
              obj.isBack = event.button
              this.$store.dispatch("getContent",obj)
          },
          getList: function () {
              this.$http.get("/index/IAN").then(function (res) {
                  var obj = {}
                  obj.value = [].concat(res.body[0],res.body[1])
                  this.$store.commit("GETLIST",obj)
                  //初始化数据
                  var event={}
                  event.id = obj.value[0]._id
                  event.type = obj.value[0].type
                  event.isBack = 0
                  this.$store.dispatch("getContent",event)
              })
          },
          goBack: function () {
              //重新自定义事件
              var self = this
              var eve = new Event("goBack",{"bubbles":true, "cancelable":false})
              window.eve = eve
              var preEle = document.getElementsByClassName("list_content")[0]
              preEle.addEventListener("goBack",function (event) {
                  if (event.target.className == "list_item"){
                      self.getContent(event)
                  }
              })
              /*var eles = document.getElementsByClassName("list_item")
              Array.from(eles).forEach(function (item) {
                  item.addEventListener("goBack",function (event) {
                      self.getContent(event)
                  })
              })*/

              if(history.pushState){
                  window.addEventListener("popstate",function () {
                      var id = location.href.split("=")[1]
                      var ele1 = document.getElementById(id)
                      if (ele1){
                          ele1.dispatchEvent(eve)
                      }
                  })
              }
          }
      },
      created(){
          this.getList()
      },
      mounted(){
          this.goBack()
      }

代码中的注释部分,只有在里面添加debugger才会执行绑定,后来没办法改成了事件代理绑定,求问出现上述的原因是什么

回到顶部