简体   繁体   English

Vue.js方法不触发

[英]Vuejs methods not firing

When i call a vuejs function from jquery selector it is not firing. 当我从jquery选择器中调用vuejs函数时,它没有触发。 I have integrate d3-dagre chart in vue component. 我已经在Vue组件中集成了d3-dagre图表。 when i set a click action for the nodes it is not firing the vuejs methods. 当我为节点设置点击动作时,不会触发vuejs方法。 In the below getJobid() is not firing. 在下面的getJobid()中不触发。 Find the below vue component code and also error in the end. 找到下面的vue组件代码,最后也出错。

Vue component: 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')
    }
  }
}

Error: 错误:

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

The this in the callback for the on handler is not referencing the Vue instance. on处理程序的回调中的this未引用Vue实例。 Set a reference outside the handler and use that instead: 在处理程序外部设置引用,并使用该引用:

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()
  })

最好使用箭头函数,以便回调函数中的this引用Vue实例。

Well, the problem here is that "this.getJobid()" actually is not a function This is referring to the current context - in your case 好吧,这里的问题是“ 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
..
}

The solution is to create a reference to the Vue before the registering of your handler, typically 解决方案是在注册处理程序之前创建对Vue的引用,通常是

const vm = this;

Then you can try 那你可以试试

vm.getJobid();
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()
  })

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

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