VueJS accessing a method from another method

后端 未结 3 1990
野趣味
野趣味 2020-12-05 05:59

I\'m using VueJS to make a simple enough resource management game/interface. At the minute I\'m looking to activate the roll function every 12.5 seconds and use

相关标签:
3条回答
  • 2020-12-05 06:40

    let vm = new Vue({
      el: '#testfunc',
      data:{
        sp1: "Hi I'm textbox1",
        sp2: "Hi I'm textbox2"
      },
      methods:{
        chsp1:function(){
          this.sp1 = "I'm swapped from textbox2"
        },
        chsp2:function(){
          this.sp2 = "I'm swapped from textbox1";
          this.chsp1();
        },
        swapit:function(){
          this.chsp2();
        }
      }
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
    <div id="testfunc">
      <input type="text" :value="sp1"></span>
      <input type="text" :value="sp2"></span>
      <button @click="swapit()">Swap</button>
    </div>

    0 讨论(0)
  • 2020-12-05 06:42

    You can use vm.methodName();

    Example:

    let vm = new Vue({
      el: '#app',
      data: {},
      methods: {
        methodA: function () {
          console.log('hello');
        },
        methodB: function () {
          // calling methodA
          vm.methodA();
        }
      },
    })
    
    0 讨论(0)
  • 2020-12-05 06:52

    You can access these methods directly on the VM instance, or use them in directive expressions. All methods will have their this context automatically bound to the Vue instance.

    – Vue API Guide on methods

    Within a method on a Vue instance you can access other methods on the instance using this.

    var vm = new Vue({
      ...
      methods: {
        methodA() {
          // Method A
        },
        methodB() {
          // Method B
    
          // Call `methodA` from inside `methodB`
          this.methodA()
        },
      },
      ...
    });
    

    To access a method outside of a Vue instance you can assign the instance to a variable (such as vm in the example above) and call the method:

    vm.methodA();
    
    0 讨论(0)
提交回复
热议问题