weex踩坑之旅第二彈 ~ 在weex中集成vue-router

接着第一彈講,咱們已經搭建好一個屬於本身的weex項目了,而後如何開發呢?因爲以前項目中都是採用vue全家桶進行開發,路由使用vue-router插件,狀態管理使用vuex,Ajax先後臺交互使用axios,圖標庫使用font-awesome,組件庫使用element-ui...可是這些插件能不能都在weex中集成呢?若是你也是一個web開發者,應該重點考慮這個問題,在瀏覽器中,咱們須要把這個 JS bundle 做爲一段 <script> 載入網頁,在客戶端裏,咱們把這段 JS bundle 載入本地,並經過 WeexSDK 直接執行。也就是說在native中,咱們的代碼是要在native環境中運行。而在native中,是沒有document,window等DOM以及BOM的,即全部的DOM,BOM框架都是不可使用的。好比jQuery相關組件,axios相關組件,element-ui等都不能在weex中引用。

vue-router是能夠在weex中使用的。若是想開發具備導航功能的頁面,能夠考慮將vue-router繼承到項目中vue

vue-router的集成

1. 安裝vue-router

$ npm install vue-router --save

2. 建立路由組件頁面

<template>
    <div class="one">
        <text>
            {{msg}}
        </text>
    </div>
</template>
<script>
    export default {
        data:()=>({
            msg:'this is one'
        })
    }
</script>

代碼結構以下ios

clipboard.png

3. 集成

在src目錄建立router目錄,用於存放路由相關信息,而後在router中新建index.js。進行路由的配置以及與Router的集成,如下是src/router/index.js的代碼web

import Router from 'vue-router'
//組件導入
import ViewOne from '../pages/one/index.vue'
import ViewTwo from '../pages/two/index.vue'
import ViewThree from '../pages/three/index.vue'
//將Vue-router繼承到Vue中
Vue.use(Router);
//提供默認對外接口
export default new Router({
  // mode: 'abstract',
  routes: [
    { path: '/one', component: ViewOne },
    { path: '/two', component: ViewTwo },
    { path: '/three', component: ViewThree }
  ]
});

而後在entry.js中導入router的配置vue-router

import App from './App.vue'
//引入路由配置
import router from './router'
new Vue(Vue.util.extend({
    el:'#root',    
    //將vue集成到vue中
    router,
},App))

4. 路由編程

在App.vue中提供<router-view>指令,用於顯示路由信息vuex

<template>
    <div class='container'>
        <!-- 標題 -->
        <div class="panel titlePanel">
            <text class='title'>{{msg}}</text>
        </div>
        <!-- 導航區 -->
      <div class="panel">
          <text class='link' @click='linkTo("/one")'>one</text>
          <text class='link' @click='linkTo("/two")'>two</text>
          <text class='link' @click='linkTo("/three")'>three</text>
      </div>
      <!-- 視圖區 -->
    <router-view></router-view>
    </div>
</template>
<script>
    export default{
        data(){
            return {
                msg:'你好,weex'
            }
        },
        methods:{
            linkTo(path){
                //點擊後改變路由
                this.$router.push(path);
            }
        }
    }
</script>
<style>
.container {
    background-color:#f4f4f4;
}

.panel {
    flex-direction: row;
    height: 100px;
    border-bottom-width: 1px;
    justify-content: space-between;
}
.titlePanel {
    justify-content: center;
    background-color: #ededed;
}
.title {
    height: 100px;
    line-height: 100px;
}
.link{
    line-height: 100px;
    text-align: center;
    flex: 1
}
</style>

運行效果npm

clipboard.png

相關文章
相關標籤/搜索