Home > front end >  How can I use the method from other component
How can I use the method from other component

Time:12-12

I want use the method 'pause()' in the component 'vue-count-to',but the webstorm tips Unresolved function or method pause() .How can I use the method in 'vue-count-to'?Thank you

<template>
  <div>
  <countTo ref="countTo1" :startVal='startVal' :endVal='endVal' :duration='3000'>

  </countTo>
  <input type="text" v-model="endVal">
    <Button v-on:click="handleClick" >reset</Button>
  </div>
</template>

<script>
import CountTox from 'vue-count-to';
export default {
  components: {
    countTo: CountTox},
  data () {
    return {
      startVal: 0,
      endVal: 2017,
      autoplay: false
    }
  },
  methods: {
    handleClick() {
      this.$refs.countTo1.pause();
    }
  }
}
</script>

CodePudding user response:

you can use $root.$emit() and $root.$on()

const componentA = {
  template: `
    <button @click="callMethodInComponentB">
      call method in component-b
    </button>
  `,
  methods: {
    callMethodInComponentB() {
      this.$root.$emit('call-to-component-b', 2);
    }
  }
}

const componentB = {
  template: `
    <h1>Value: {{ value.toString() }}</h1>
  `,
  data(){
    return {
      value: 0
    }
  },
  methods: {
    plus(add) {
      this.value  = add
    }
  },
  mounted() {
    this.$root.$on('call-to-component-b', add => {
       this.plus(add)
    });
  }
};


new Vue({
  el: '#app',
  components: {
    componentA,
    componentB
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<main id="app">
   <component-a></component-a>
   <component-b></component-b>
</main>

CodePudding user response:

define the method in App.vue and access it from probs and emit

  • Related