如何在vue csp的“方法”对象中放置更多对象或类。

时间:2019-07-17 13:54:21

标签: vue.js

我有一个使用Vue csp的Chrome扩展程序

我这样实例化它:

class MyMethods {
  testMe(){}
  anotherFunction(){}
}

const methods = new MyMethods();

const app = new Vue({
  el: '#app',
  data: () => appData,
  methods
});

而且可行,我可以在模板(html文件)中使用testMe()anotherFunction()

<button v-on:click="testMe()">testMe()</button>
<button v-on:click="anotherFunction()">anotherFunction()</button>

但是我想将其细分为更多类,例如MyMethodsXMyMethodsY,以便在需要时可以对其进行扩展。

但是我找不到让Vue理解我不仅有对象而且有对象对象的任何方法。那就是我想对与以下功能相同的功能进行分组:

<button v-on:click="tests.testMe()">testMe()</button>
<button v-on:click="handling.anotherFunction()">anotherFunction()</button>

我尝试过:

const app = new Vue({
  el: '#app',
  data: () => appData,
  methods : {
      methodsX: new MyMethods()
  }
});

class MyWrapperClass() {
  methodsX = new MyMethods()
}
const app = new Vue({
  el: '#app',
  data: () => appData,
  methods : new MyWrapperClass()
});

但是我无法调用testMe(),它总是说“无法读取未定义的属性'apply'”。

有没有一种方法可以将新的名称空间/类/对象放入Vue应用的“方法”键中?

编辑:

我的最终目标是拥有这样的东西:

<div class="tests" v-if="testing">
    <button :click="testing.test1()>Testing Uno</button>
    <button :click="testing.test2()>Testing Dos</button>
</div>
<div class="handling" v-if="handling">
    <button :click="handling.func1()>Handling Uno</button>
    <button :click="handling.func2()>Handling Dos</button>
</div>

其中每个类别都是具有自己的方法的类(可能还包括测试:))

1 个答案:

答案 0 :(得分:1)

我可能会误解您的用例,但我认为您不想在class中组合功能。如果我对您的理解正确,那么您希望能够创建一个函数集合,其他事物可以将它们当作方法使用。在那种情况下,我认为您应该采用混合方法。

与其创建具有方法集合的class,不如创建具有所有功能的简单Object,然后将它们传播到想要拥有它们的对象上:

const appData = {
  foo: "bar"
};

const MyMethods = {
  me() {
    return "me";
  }
};

const YourMethods = {
  you() {
    return "you";
  }
};

const methods = {
  ...MyMethods,
  ...YourMethods
};

const app = new Vue({
  el: '#app',
  data: () => appData,
  methods
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">{{me()}} | {{you()}}</div>