Vue.js: Import class with function and call it in

2019-08-26 13:02发布

问题:

I have a component my-parent. In this component, I use a child component my-child and import an external class MyClass with an own function exportedFunction. I tried to use this solution: VueJS accessing externaly imported method in vue component

Basiclly, I use mounted and the name of the function from the imported class. In methods I defined a new method, which calls the mounted one from the imported class. Than I pass the created method as property to my child, where I try to call the function with a @click and pass the parameter there.

Here is my code so far:

my-parent template:

<template>
    <my-child :exportedFunction="callFunction"></my-child>
</template>

<script>
import MyClass from './MyClass';

export default {
    mounted() {
        exportedFunction()
    },
    methods: {
        callFunction() {
            exportedFunction()
        }
    }
}
</script>

my-child template:

<template>
    <button @click="exportedFunction('hello world!')">Click me!</button>
</template>

<script>
export default {
    props: ['exportedFunction']
}
</script>

MyClass code:

export default class MyClass {
    exportedClass(parameter) {
        console.log(parameter) // expected 'hello world' from child
    }
}

Hope for some help!

回答1:

I would ditch your MyClass component and instead have:

my-parent

<template>
    <my-child :triggerEvent="callFunction"></my-child>
</template>

<script>
export default {
    methods: {
        callFunction() {
          console.log('hello');
        }
    }
}
</script>

my-child

<template>
    <button @click="$emit('triggerEvent')">Click me!</button>
</template>

As you want to use MyClass in your example you can keep it as is and have my-parent as:

<template>
  <my-child :triggerEvent="callFunction"/>
</template>

<script>
import MyChild from "./MyChild";
import MyClass from "./MyClass.js";

export default {
  components: {
    MyChild
  },
  data() {
    return {
      myCls: new MyClass()
    };
  },
  mounted() {
    this.myCls.exportedClass("hello my class");
  },
  methods: {
    callFunction() {
      console.log("hello");
    }
  }
};
</script>