最近在看關(guān)于跨端開發(fā)的技術(shù)嵌器,出現(xiàn)在視野里較多的關(guān)鍵字React Native肛真、WEEX、Flutter爽航,不論宣傳的其他亮點再多蚓让,也掩蓋不了WEEX一份代碼三端運行的光芒乾忱,但真正想去入手的時候發(fā)現(xiàn)資料還真不多。這里總結(jié)下在學習WEEX過程中可能會發(fā)出的幾個疑問:
如何快速創(chuàng)建一個Weex應(yīng)用
官方提供了一個手腳架命令行工具weex-toolkit用于創(chuàng)建weex項目
全局安裝weex-toolkit
$ npm install -g weex-toolkit
創(chuàng)建一個項目使用create
命令,按提示輸入創(chuàng)建項目
$ weex create my-project
具體也可參照官方提供的文檔快速上手
在WEEX中如何做頁面跳轉(zhuǎn)(多頁應(yīng)用)
WEEX中提供了一個內(nèi)置模塊navigator來來實現(xiàn)頁面切換历极。
頁面跳轉(zhuǎn)需要分端進行窄瘟,在h5中url為頁面鏈接,在移動APP中的url則為打包后生成的js bundle文件,已跳轉(zhuǎn)一個詳情頁為例
h5:
var navigator = weex.requireModule('navigator')
navigator.push({
url: '/detail.html?id=xxxx',
animated: "true"
});
Android or IOS
var navigator = weex.requireModule('navigator')
navigator.push({
url: '/detail.js?id=xxxx',
animated: "true"
});
可以通過weex.config.env.platform變量來獲取當前運行的平臺,當然在實際項目中這樣的跳轉(zhuǎn)方式太麻煩彼乌,因為這樣我們每個頁面切換都需要識別平臺识啦。
正確做法可以跟客戶端開發(fā)的同學商定跳轉(zhuǎn)協(xié)議,如客戶端攔截到/detail.html時自動去完成detail.js的下載并渲染蘸炸。
如何使用或擴展一個模塊
weex已經(jīng)內(nèi)置了部分模塊詳見weex內(nèi)置模塊
使用方法:
var module = weex.requireModule('模塊名')
注冊一個模塊
如果你引入了 weex-vue-render
這個庫,那么在全局能獲取到 weex
這個變量,其中提供了 registerModule
方法可以注冊模塊琼稻。
API格式
registerModule
name
: {String} 必選,模塊名稱饶囚。
define
: {Object} 必選帕翻,模塊的定義。
meta:
{Object} 可選萝风,如果你需要將非 iterable 的屬性或方法注冊到模塊對象里嘀掸,你才需要用到這個參數(shù),將 { registerType: 'assignment' }
作為 meta 參數(shù)傳入即可规惰。
下邊注冊一個名為guide
的模塊
import Vue from 'vue';
import weex from 'weex-vue-render';
weex.init(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.')
}
})
使用 guide
模塊:
// 獲取模塊
const guide = weex.requireModule('guide')
// 可以直接調(diào)用模塊中的方法
guide.greeting()
guide.farewell()
當然如果代碼是跑在客戶端中那么需要客戶端同時實現(xiàn)并注冊名稱參數(shù)一樣的模塊以供調(diào)用睬塌。
需要說明的是,內(nèi)置模塊是可以重新注冊的歇万,也就是覆蓋注冊揩晴,比如內(nèi)置模塊modal
中提供了toast方法,但樣式不滿足實際項目中的視覺需求贪磺,因此我們可以重新實現(xiàn)并覆蓋硫兰。
import Vue from 'vue';
import weex from 'weex-vue-render';
const modal = weex.requireModule('modal')
import toast from '@/components/common/Toast/index'
weex.init(Vue);
weex.registerModule('modal', {
...modal,
toast
})
如何擴展內(nèi)置組件
以擴展 <sidebar>
為例,首先應(yīng)該編寫組件自身的邏輯:
<!-- sidebar.vue -->
<template>
<div class="sidebar">
<slot></slot>
</div>
</template>
<style scoped>
.sidebar {
/* ... */
}
</style>
<script>
export default {
props: [],
data () {
return {}
}
}
</script>
然后在使用之前寒锚,全局注冊 <sidebar>
組件:
import Vue from 'vue'
import weex from 'weex-vue-render'
import Sidebar from './path/to/sidebar.vue'
weex.init(Vue)
// 全局注冊 sidebar 組件
weex.registerComponent('sidebar', Sidebar)
// 或者使用 Vue.component
Vue.component('sidebar', Sidebar)
附上一個自己寫的的包含首頁劫映、列表頁、詳情頁|數(shù)據(jù)請求刹前、頁面跳轉(zhuǎn)的簡單demo
https://github.com/longyunxia/weex-demo