| 3 min read

WEEX在今年一月份宣布在web端对vue渲染的支持,也就是说,今后你可以用写vue的的方式去写weex 项目。在升级新版的weex的时候大家一定记得去官网看下diff

[Weex 和 Vue 2.x 的语法差异]https://weex-project.io/cn/references/migration/difference.html。

如果我们在开发第三方插件的时候,我们同样需要注意对与插件写法上的差异。

第三方组件

老版本我们在第三方组件的时候,大致是这样的:


// 设置 标签属性 
const attr = {  
  // ...
}
// 设置样式
const style = {  
  // ...
}

// 设置事件响应
const event = {  
  // ...
}
// 初始化函数
function init (Weex) {  
  const Component = Weex.Component
  const extend = Weex.utils.extend

  // the component's constructor
  function Hello (data) {
    Component.call(this, data)
  }

  // extend the prototype
  Hello.prototype = Object.create(Component.prototype)
  extend(Hello.prototype, proto)
  // 注册组件
  Weex.registerComponent('weex-hello', Hello)
}

// export the init method.
export default { init }  

其中值得关注的是你需要导出一个init函数,因为我们在使用插件的时候需要执行install函数,里面会默认执行你导出对象的init函数。

import polaroidPhoto from 'weex-polaroid-photo-web'  
// install the component.
weex.install(polaroidPhoto)

而如果你用vue写第三方组件的话,你就只需要Vue.component

import Vue from 'vue'
import Hello from './path/to/hello.vue'
// 全局注册 sidebar 组件
Vue.component('weex-hello', Hello)

第三方模块扩展

我们除了扩展组件外,我们还可以扩展第三方模块。weex 内部提供了modal,storage,webview等。如果是老板的weex模块我们可以这样写,

const confirm = {  
  // 定义用户登录方法.
  ask (msg, callbackId) {
    if(window.confirm(msg)) {
      this.sender.performCallback(callbackId)
    }
  },
}

const meta = {  
  confirm: [{
    name: 'ask',
    args: ['string', 'function']
  }]
}

export default {  
  init (Weex) {
    // 注册这个模块,最后一个参数是模块的元信息.
    Weex.registerApiModule('confirm', confirm, meta)
  }
}

和组件一致,我们需要导出init函数,便于在weex.install的时候执行钩子。在.we的文件中我们需要这样调用模块:

var confirm = require('@weex-module/confirm')
  module.exports = {
    methods: {
      handleClick: function () {
        confirm.ask('are u ok?', function () {
          // ... do sth. in callback.
        })
      }
    }
  }

而在vue中我们开发第三方模块需要修改成这样:

weex.registerModule('guide', {
  greeting () {
    console.log('Hello, nice to meet you. I am your guide.')
  },
  farewell () {
    console.log('Goodbye, I am always at your service.')
  }
})

在vue中我们需要这样引入:

// 获取模块
const guide = weex.requireModule('guide')
// 可以直接调用模块中的方法
guide.greeting()
guide.farewell()

一张表格进行对比

功能 vue weex
注册组件 Vue.component('weex-hello', Hello) Weex.registerComponent('weex-hello', Hello)
注册模块 weex.registerModule('confirm, confirm) Weex.registerApiModule('confirm', confirm, meta)
使用模块 weex. weex.requireModule('confirm) var confirm = require('@weex-module/confirm')

同时兼容写法

不太推荐这样的写法,但是如果你要坚持的话,可以参考weex-action-sheet.

我们会将web目录进行build的,在入口文件通过window.Vue来进行判断从而选择怎样注册模块。

You Can Speak "Hi" to Me in Those Ways