【问题标题】:How put more objects or clases inside the "methods" object in vue csp?如何在 vue csp 中的“方法”对象中放入更多对象或类?
【发布时间】:2019-07-17 13:54:21
【问题描述】:

我有一个使用 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() 它总是说“无法读取未定义的属性'应用'”。

有没有办法做到这一点,以便我可以将新的命名空间/类/对象放入 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>

每个类别都是一个有自己的方法的类(可能还有测试:))

【问题讨论】:

  • 在第一个示例中,您如何称呼testMe()?每当我尝试调用它时,都会出现错误。
  • @zero298 我已经更新了我的问题:)
  • 根据this answer,你可以做到,但我做不到

标签: vue.js


【解决方案1】:

我可能误解了您的用例,但我认为您不想在 class 中组合您的函数。如果我对您的理解正确,您希望能够创建其他东西可以使用的函数集合,就好像它们是方法一样。在这种情况下,我认为您应该采用 mixin 方法。

不要创建一个包含方法集合的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>

【讨论】:

  • 本来打算写一样的
  • 嗨@zero298,谢谢你的回答。我已经更新了我的问题。我想我不清楚我的用例。
猜你喜欢
  • 1970-01-01
  • 2021-05-24
  • 1970-01-01
  • 2011-03-25
  • 2022-11-02
  • 1970-01-01
  • 2013-12-03
  • 2017-11-08
  • 1970-01-01
相关资源
最近更新 更多