Vuejs使用事件发射器

时间:2018-01-16 20:23:04

标签: javascript vue.js vuejs2

我正在尝试使用Vue 2.x使用事件发射器的内容更新数据变量? (不确定这是否是正确的术语)。

示例:

<script>
var exec = require('child_process').exec;

export default {
  data () {
    return {
      output: ''
    }
  },
  methods: {
    test () {
      this.output = '';

      var myProcess = exec('"./jre/bin/java.exe" -jar -Xmx1024m -Xms256m -Dfile.encoding=UTF8 "./eu_datamatcher.jar" "./runtime.properties"', { cwd: './datamatcher/' });

      myProcess.stdout.on('data', function(data) { 
         // This line isn't correct since this.output is not assigned   
         this.output += data.toString();
      });
    }
  }
}
</script>

如何在.on事件中更新数据变量?

谢谢!

2 个答案:

答案 0 :(得分:0)

使用fat arrow保留this

的上下文
myProcess.stdout.on('data', (data) => {
   this.output += data.toString()
})

或者您可以使用.bind()

myProcess.stdout.on('data', function(data) {

}.bind(this))

您可以阅读更多about arrow functions on the MDN

答案 1 :(得分:0)

如果没有测试,我会建议这两种可能性:

绑定此

<script>
var exec = require('child_process').exec;

export default {
  data () {
    return {
      output: ''
    }
  },
  methods: {
    test () {
      this.output = '';

      var myProcess = exec('"./jre/bin/java.exe" -jar -Xmx1024m -Xms256m -Dfile.encoding=UTF8 "./eu_datamatcher.jar" "./runtime.properties"', { cwd: './datamatcher/' });

      myProcess.stdout.on('data', function(data) { 
         // This line isn't correct since this.output is not assigned   
         this.output += data.toString();
      }.bind(this)); // now the outer this context (including output) is available
    }
  }
}
</script>

或使用功能范围

<script>
var exec = require('child_process').exec;

export default {
  data () {
    return {
      output: ''
    }
  },
  methods: {
    test () {
      var outputReference = this.output; // This should work because output is an observerObject and so only the pointer should be stored; not quite sure right now...


      var myProcess = exec('"./jre/bin/java.exe" -jar -Xmx1024m -Xms256m -Dfile.encoding=UTF8 "./eu_datamatcher.jar" "./runtime.properties"', { cwd: './datamatcher/' });

      myProcess.stdout.on('data', function(data) { 
         // This line isn't correct since this.output is not assigned   
         outputReference += data.toString();
      });
    }
  }
}
</script>

我希望我做对了。祝你好运