weexapp 开发流程(二)框架搭建

1.创建 入口文件

src / entry.js

/**
 * 入口文件
 */
import App from './App.vue'
import router from './router'
// import { sync } from 'vuex-router-sync'
import * as filters from './filters'
import mixins from './mixins'

// sync the router with the vuex store.
// this registers `store.state.route`
// sync(store, router)

// register global utility filters.
Object.keys(filters).forEach(key => {
    Vue.filter(key, filters[key])
})

// register global mixins.
Vue.mixin(mixins)

import VueResource from 'vue-resource'
Vue.use(VueResource)
// create the app instance.
// here we inject the router and store to all child components,
// making them available everywhere as `this.$router` and `this.$store`.
new Vue(Vue.util.extend({ el: '#root', router }, App));

router.push('/');

2.创建 主页面 底部选项卡 工具类

(1)创建主页面

src / App.vue

<!-- 主页面 底部选项卡 -->
<template>
  <div class="app-wrapper">
    <router-view class="r-box"></router-view>
    <tab-bar @tabTo="onTabTo"></tab-bar>
  </div>
</template>

<style>
  body{
    margin: 0;
    padding: 0;
    background-color: #f4f4f4;
    color:#333;
  }
</style>

<style scoped>
  .app-wrapper{
    background-color: #f4f4f4;
  }
  .r-box{
    position: absolute;
    top:0;
    left: 0;
    right: 0;
    bottom: 0;
  }
</style>

<script>
  // 弹窗
  var modal = weex.requireModule('modal');
  // 工具类
  import util from './assets/util';
  // 底部选项卡组件
  import tabBar from './assets/components/tabBar.vue';
  
  export default {
    data () {
      return {
      }
    },
    components: {
      'tab-bar': tabBar
    },
    created () {
      util.initIconFont();
    },
    methods: {
      onTabTo(_result){
        let _key = _result.data.key || '';
        this.$router && this.$router.push('/'+_key)
      }
    }
  }
</script>

(2)创建 底部选项卡 组件

src / assets / components / tabBar.vue

<!-- 底部选项卡 组件 -->
<template>
  <div class="wrapper">
    <div class="bar-item" @click="tabTo('home')">
      <text class="bar-ic iconfont" :style="testCS"></text>
      <text class="bar-txt">首页</text>
    </div>
    <div class="bar-item" @click="tabTo('top')">
      <text class="bar-ic iconfont"></text>
      <text class="bar-txt">推荐</text>
    </div>
    <div class="bar-item act" @click="tabTo('demo')">
      <text class="bar-ic iconfont"></text>
      <text class="bar-txt">分类</text>
    </div>
    <div class="bar-item" @click="tabTo('all')">
      <text class="bar-ic iconfont"></text>
      <text class="bar-txt">PHP教程</text>
    </div>
    <div class="bar-item" @click="tabTo('my')">
      <text class="bar-ic iconfont"></text>
      <text class="bar-txt">关于</text>
    </div>
  </div>
</template>

<style scoped>
  .iconfont {
    font-family:iconfont;
  }
  .wrapper{
    position: fixed;
    bottom: 0;
    left: 0;right: 0;
    height: 90px;
    flex-wrap: nowrap;
    flex-direction: row;
    justify-content: space-around;
    border-top-width: 1px;
    border-top-color: #d9d9d9;
    background-color: #fafafa;
  }
  .bar-item{
    flex: 1;
  }
  .bar-txt,.bar-ic{
    color:#666;
    text-align: center;
  }
  .bar-active{
    color:#b4282d;
  }
  .bar-ic{
    padding-top: 7px;
    font-size: 38px;
  }
  .bar-txt{
    font-size: 22px;
    padding-top: 1px;
  }
</style>

<script>
  // 弹窗
  var modal = weex.requireModule('modal');

  export default {
    computed:{
      testCS:function () {
        return this.pIndexKey == 'home'?'color:#b4282d;':''
      }
    },
    data () {
      return {
        pIndexKey:'home'
      }
    },
    mounted(){
    },
    methods: {
      tabTo(_key){
        if(this.pIndexKey == _key) return;
        this.pIndexKey = _key;
        this.$emit('tabTo',{
          status : 'tabTo',
          data : {
            key : _key
          }
        })
      }
    }
  }
</script>

其他页面,例如:首页

src / assets / views / home.vue

<!-- 首页 -->
<template>
  <div>
  	<text>首页</text>
  </div>
</template>

<style scoped>
	
</style>

<script>  
  export default {
    data () {
      return {
      }
    }
  }
</script>

(3)创建 工具类

src / assets / util.js

/**
 * 工具类
 */
let utilFunc = {
    initIconFont () {
        let domModule = weex.requireModule('dom');
        domModule.addRule('fontFace', {
            'fontFamily': "iconfont",
            'src': "url('http://at.alicdn.com/t/font_493435_f28oeelm5i8xs9k9.ttf')"
        });
    },
    setBundleUrl(url, jsFile) {
        const bundleUrl = url;
        let host = '';
        let path = '';
        let nativeBase;
        const isAndroidAssets = bundleUrl.indexOf('your_current_IP') >= 0 || bundleUrl.indexOf('file://assets/') >= 0;
        const isiOSAssets = bundleUrl.indexOf('file:///') >= 0 && bundleUrl.indexOf('WeexDemo.app') > 0;
        if (isAndroidAssets) {
            nativeBase = 'file://assets/dist';
        } else if (isiOSAssets) {
            // file:///var/mobile/Containers/Bundle/Application/{id}/WeexDemo.app/
            // file:///Users/{user}/Library/Developer/CoreSimulator/Devices/{id}/data/Containers/Bundle/Application/{id}/WeexDemo.app/
            nativeBase = bundleUrl.substring(0, bundleUrl.lastIndexOf('/') + 1);
        } else {
            const matches = /\/\/([^\/]+?)\//.exec(bundleUrl);
            const matchFirstPath = /\/\/[^\/]+\/([^\s]+)\//.exec(bundleUrl);
            if (matches && matches.length >= 2) {
                host = matches[1];
            }
            if (matchFirstPath && matchFirstPath.length >= 2) {
                path = matchFirstPath[1];
            }
            nativeBase = 'http://' + host + '/';
        }
        const h5Base = './index.html?page=';
        // in Native
        let base = nativeBase;
        if (typeof navigator !== 'undefined' && (navigator.appCodeName === 'Mozilla' || navigator.product === 'Gecko')) {
            // check if in weexpack project
            if (path === 'web' || path === 'dist') {
                base = h5Base + '/dist/';
            } else {
                base = h5Base + '';
            }
        } else {
            base = nativeBase + (!!path? path+'/':'');
        }

        const newUrl = base + jsFile;
        return newUrl;
    },
    getUrlSearch(url,name) {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
        var r = url.slice(url.indexOf('?')+1).match(reg);
        if (r != null) {
            try {
                return decodeURIComponent(r[2]);
            } catch (_e) {
                return null;
            }
        }
        return null;
    }
};

export default utilFunc;

3.创建 路由

src / router.js

/**
 * 配置路由
 */
import Router from 'vue-router'
// 首页
import ViewHome from './assets/views/home.vue'
// 关于
import ViewMy from './assets/views/my.vue'
// PHP教程
import ViewAll from './assets/views/all.vue'
// 分类
import Viewdemo from './assets/views/demo.vue'
// 推荐
import ViewTopbvive from './assets/views/top.vue'

Vue.use(Router)


export default new Router({
    // mode: 'abstract',
    routes: [
    	// 默认页面 首页
        {
        	path: '/',
        	redirect: '/home'
        },
        // 首页
        {
        	path: '/home',
        	component: ViewHome
        },
        // 关于
        {
        	path: '/my',
        	component: ViewMy
        },
        // 分类
        {
        	path: '/demo',
        	component: Viewdemo
        },
        // PHP教程
        {
        	path: '/all',
        	component: ViewAll
        },
        // 推荐
        {
        	path: '/top',
        	component: ViewTopbvive
        }
    ]
})

4.创建 公用过滤器 filters

src / filters / index.js

export function host (url) {
  if (!url) return ''
  const host = url.replace(/^https?:\/\//, '').replace(/\/.*$/, '')
  const parts = host.split('.').slice(-3)
  if (parts[0] === 'www') parts.shift()
  return parts.join('.')
}

export function https (url) {
  const env = weex.config.env || WXEnvironment
  if (env.platform === 'iOS' && typeof url === 'string') {
    return url.replace(/^http\:/, 'https:')
  }
  return url
}

export function timeAgo (time) {
  const between = Date.now() / 1000 - Number(time)
  if (between < 3600) {
    return pluralize(~~(between / 60), ' minute')
  } else if (between < 86400) {
    return pluralize(~~(between / 3600), ' hour')
  } else {
    return pluralize(~~(between / 86400), ' day')
  }
}

function pluralize (time, label) {
  if (time === 1) {
    return time + label
  }
  return time + label + 's'
}

export function unescape (text) {
  let res = text || ''

  ;[
    ['<p>', '\n'],
    ['&', '&'],
    ['&', '&'],
    [''', '\''],
    [''', '\''],
    ['/', '/'],
    [''', '\''],
    ['/', '/'],
    ['<', '<'],
    ['>', '>'],
    [' ', ' '],
    ['"', '"']
  ].forEach(pair => {
    res = res.replace(new RegExp(pair[0], 'ig'), pair[1])
  })

  return res
}

5.创建 混合 mixins

src / mixins / index.js

export default {
  methods: {
    jump (to) {
      if (this.$router) {
        this.$router.push(to)
      }
    }
  }
}

6.效果图

posted @ 2017-12-17 00:01  每天都要进步一点点  阅读(483)  评论(0)    收藏  举报