【问题标题】:Vue.js: Import class with function and call it in child componentVue.js:使用函数导入类并在子组件中调用它
【发布时间】:2019-10-11 02:27:04
【问题描述】:

我有一个组件my-parent。在这个组件中,我使用了一个子组件my-child 并导入了一个外部类MyClass 和一个自己的函数exportedFunction。我尝试使用此解决方案:VueJS accessing externaly imported method in vue component

基本上,我使用mounted 和导入类中的函数名称。在methods 中,我定义了一个新方法,它从导入的类中调用挂载的方法。然后我将创建的方法作为属性传递给我的孩子,在那里我尝试使用@click 调用该函数并在那里传递参数。

到目前为止,这是我的代码:

my-parent模板:

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

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

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

my-child模板:

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

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

MyClass代码:

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

希望得到一些帮助!

【问题讨论】:

  • 有什么理由为什么在子组件中你不发出你在父组件中监听的事件并在那里触发方法?
  • @Manu 因为我真的是 Vue.Js 的新手,所以不知道有这样的方法。在这个例子中我该怎么做?

标签: javascript class vue.js properties vue-component


【解决方案1】:

我会放弃你的 MyClass 组件,而是拥有:

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>

由于您想在示例中使用MyClass,您可以保持原样并将my-parent 设置为:

<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>

【讨论】:

  • 另外,请确保在您的 my-parent 组件中导入您的 my-child 组件
  • 谢谢!但我必须将MyClass 与该功能一起使用。那么我可以从父组件调用MyClass 中的函数吗?所以我会emit 来自孩子的调用并从父组件调用MyClass 中的函数?这可能吗?
  • 你打算重复使用MyClass吗?如果是这样,我们可以使用 mixin。只是想知道它的用途。
  • @MrBuggy,我已经更新了我的答案以使用MyClass。最好了解其背后的原因,因为您可能希望使用 mixin - 以获得最佳实践。
  • @MrBuggy,好吧,有道理,以上应该可以满足您的需求。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-05-16
  • 2023-01-23
  • 2021-02-25
  • 2023-01-10
  • 1970-01-01
  • 1970-01-01
  • 2016-08-17
相关资源
最近更新 更多