【问题标题】:Vuejs methods not firingVuejs方法没有触发
【发布时间】:2017-08-09 14:27:56
【问题描述】:

当我从 jquery 选择器调用 vuejs 函数时,它不会触发。我已经在 vue 组件中集成了 d3-dagre 图表。当我为节点设置点击操作时,它不会触发 vuejs 方法。在下面的 getJobid() 没有触发。找到下面的vue组件代码,最后还是报错。

Vue 组件:

export default {
  name: 'dagView',
  created () {
    console.log('test2')
  },
  mounted () {
     var g = new dagreD3.graphlib.Graph().setGraph({})
     // Create the renderer    
     var render = new dagreD3.render()

     // Set up an SVG group so that we can translate the final graph.
     var svg = d3.select("svg"),
     inner = svg.append("g")

     // Run the renderer. This is what draws the final graph.
     render(inner, g)

     inner.selectAll("g.node")
     .on("click", function(v) {
        console.log("Nodes --> "+ v + " -- "+ g.node(v).label)
        this.nodeId = g.node(v).label
        console.log("Node id -- "+ this.nodeId)
        this.getJobid()
     })
  },
  methods: {
    getJobid: function() {
      console.log('Received NodeId')
    }
  }
}

错误:

Uncaught TypeError: this.getJobid is not a function
at SVGGElement.eval (DAG.vue?2ccc:180)
at SVGGElement.__onclick (d3.v3.min.js:1)

【问题讨论】:

  • this.getJobid 在您显示的代码中的任何地方都没有调用
  • @thanksd 更新了您现在可以验证的代码

标签: jquery d3.js vue.js vuejs2 dagre-d3


【解决方案1】:

on 处理程序的回调中的 this 未引用 Vue 实例。在处理程序之外设置一个引用并改用它:

var self = this 
inner.selectAll("g.node")
  .on("click", function(v) {
    console.log("Nodes --> "+ v + " -- "+ g.node(v).label)
    self.nodeId = g.node(v).label
    console.log("Node id -- "+ this.nodeId)
    self.getJobid()
  })

【讨论】:

【解决方案2】:

最好使用arrow function,以便回调中的this 引用Vue 实例。

【讨论】:

    【解决方案3】:

    好吧,这里的问题是“this.getJobid()”实际上不是一个函数 这是指当前上下文-在您的情况下

    inner.selectAll("g.node").on("click", function(v) {
    // as we are inside inner.selectAll('g.node') 
    // our Vue instance is not what we will find here
    ..
    }
    

    解决方案是在注册处理程序之前创建对 Vue 的引用,通常是

    const vm = this;
    

    那你可以试试

    vm.getJobid();
    

    【讨论】:

      【解决方案4】:
      inner.selectAll("g.node")
        .on("click", (v) => {
          console.log("Nodes --> " + v + " -- " + g.node(v).label)
          this.nodeId = g.node(v).label
          console.log("Node id -- " + this.nodeId)
          this.getJobid()
        })
      

      【讨论】:

      猜你喜欢
      • 2017-09-15
      • 2018-04-30
      • 1970-01-01
      • 2020-08-02
      • 1970-01-01
      • 1970-01-01
      • 2020-08-03
      • 2012-12-06
      • 2018-09-21
      相关资源
      最近更新 更多