简介
vue-router是vue.js提供的路由插件。
这里主要是用来支持页面跳转。
操作
添加文件及其代码
创建路由
//src/router.js
import Router from 'vue-router'
import CounterView from './views/Counter.vue'
import CounterSView from './views/CounterStore.vue'
import Hello from './views/Hello.vue'
Vue.use(Router)
export default new Router({
// mode: 'abstract',
routes: [
{ path: '/counter', component: CounterView },
{ path: '/counters', component: CounterSView },
{ path: '/hello', component: Hello },
{ path: '/', redirect: '/hello' }
]
})
将路由插入vue
//src/entry.js
var vm = new Vue(Vue.util.extend(
{ el: '#root',
store,
router,//<----
}, App))
//src/App.vue
<template>
<div @androidback="back">
<p>
<router-link to="/bar">Go to Bar</router-link>
<router-link to="/counter">counter</router-link>
<router-link to="/hello">hello</router-link>
</p>
<router-view style="flex:1"></router-view>
</div>
</template>
<script>
export default {
methods: {
back: function () {
this.$router.back()
}
}
}
</script>
此时运行浏览器可以看到路由效果。但是native时不能用,weex文档中提到native不支持有两点:
- ul、li等标签。
- vue-router不能支持导航链接,只支持编程式导航
so,修改如下
//src/App.vue
<template>
<div @androidback="back">
<list class="list">
<cell class="cell" @click="jump('/hello')">
<text>hello<text>
</cell>
<cell class="cell" @click="jump('/')">
<text>/<text>
</cell>
<cell class="cell" @click="jump('/counter')">
<text>counter<text>
</cell>
</list>
<router-view style="flex:1"></router-view>
</div>
</template>
//serc/mixins/index.js
export default {
methods: {
jump (to) {
console.log('to='+to);
if (this.$router) {
this.$router.push(to)
}
}
}
}
import mixins from './mixins'
//src/entry.js
Vue.mixin(mixins)
Vue.mixin是Vue的混合组建。上面使用全局注册混合对象。 注意使用! 一旦使用全局混合对象,将会影响到 所有 之后创建的 Vue 实例。使用恰当时,可以为自定义对象注入处理逻辑。
so,每一个vue的实例都有了jump方法。
浏览器运行正常,native依然失败。原因未知,经过多次试验,将jump放到router-view中调用则无问题。
修改代码如下:
//src/App.vue
<template>
<div @androidback="back">
<router-view style="flex:1"></router-view>
</div>
</template>
//src/views/Helle.vue
<div class="wrapper" @click="jump('/counter')">
//src/views/Counter.vue
<button @click="jump('/hello')">Increment async</button>
native可实现两个页面互相跳转。至于原因,初学还未知,以后学到了回来补上。
结构目录也发生了变化。将原来components=>views下
views下放页面。
components下放组件。
api下放异步回调方法,比如http请求。
至此大体的框架已经有了,之后还会持续修改。比如有博客说用weex不建议用vue-router做页面跳转,建议使用多页面做跳转。