在面板中使用 Vue

如果你已经掌握了 编写面板界面 这章中的界面编写方法,你或许会觉得这样编写界面有些繁琐。是否能够使用一些前端界面框架来提升界面编写效率呢?答案是肯定的。Cocos Creator支持任何界面框架如 VueReactPolymer 等等。

在测试过程中,我们发现 Vue 非常符合 Cocos Creator 的整体设计思路,所以我们重点介绍一下如何在 Cocos Creator 中使用 Vue 编写面板界面。

部署 Vue

事实上你不用做任何准备工作,Cocos Creator 的面板窗口在打开时就会默认加载 Vue。

初始化 Vue 面板

我们可以在 ready() 函数中初始化 Vue 面板。初始化方式如下:

  1. ready () {
  2. new window.Vue({
  3. el: this.shadowRoot,
  4. });
  5. }

通过传入 panel-frame 的 shadow root 元素,我们可以让 Vue 在该元素节点下生成一份 vm。让我们来看一个更详细的使用例子:

  1. Editor.Panel.extend({
  2. style: `
  3. :host {
  4. margin: 10px;
  5. }
  6. `,
  7. template: `
  8. <h2>A Simple Vue Panel</h2>
  9. <input v-model="message">
  10. <p>Input Value = <span>{{message}}</span></p>
  11. `,
  12. ready () {
  13. new window.Vue({
  14. el: this.shadowRoot,
  15. data: {
  16. message: 'Hello World',
  17. },
  18. });
  19. },
  20. });

数据绑定

我们可以在面板的 template 关键字中,定义 Vue 的数据绑定规则。然后通过在 Vue 定义的 data 关键字中写入绑定数据来完成整个操作。

具体例子如下:

  1. Editor.Panel.extend({
  2. template: `
  3. <ui-button>{{txtOK}}</ui-button>
  4. <ui-button v-if="showCancel">{{txtCancel}}</ui-button>
  5. <ui-input v-for="item in items" value="{{item.message}}"></ui-input>
  6. `,
  7. ready () {
  8. new window.Vue({
  9. el: this.shadowRoot,
  10. data: {
  11. txtOK: 'OK',
  12. txtCancel: 'Cancel',
  13. showCancel: false,
  14. items: [
  15. { message: 'Foo' },
  16. { message: 'Bar' },
  17. ]
  18. },
  19. });
  20. },
  21. });

事件绑定

除了使用数据绑定,我们还可以通过 Vue 的 @ 方式来将事件和方法绑定在一起。值得注意的是,绑定的方法必须定义在 Vue 定义中的 methods 关键字中。

具体例子如下:

  1. Editor.Panel.extend({
  2. template: `
  3. <ui-button @confirm="onConfirm">Click Me</ui-button>
  4. `,
  5. ready () {
  6. new window.Vue({
  7. el: this.shadowRoot,
  8. methods: {
  9. onConfirm ( event ) {
  10. event.stopPropagation();
  11. console.log('On Confirm!');
  12. },
  13. },
  14. });
  15. },
  16. });