Vue单页应用的跳转,大部分使用Vue-router。要理解Vue-router的原理,首先要会Vue自带的<component>
元素。
<component>
的用法很简单,只要对其 is 特性进行动态绑定,<component>
动态切换成多个组件。
下面我们来实现这样一个功能:
结构.PNG
核心的东西是两个页面根据实际相互跳转,而且不需要刷新页面。
管理页面的框架,前面已经实现,下面实现一个登录页面框架。
在components
目录下新建Login.vue
。
为了说清楚事情,只实现一个按钮
<template>
<div class="login">
<div><el-button type="primary" @click="submit">登录</el-button></div>
</div>
</template>
<script>
export default {
methods: {
submit() {
// 向上级组件发送一个redirec事件,事件参数为'/index.json'
this.$emit('redirect', '/index.json');
},
},
};
</script>
<style scoped>
.login {
display: flex;
flex: 1;
background-color: dimgrey;
}
</style>
Admin
组件也相应的修改下
<el-header height="80px"><el-button type="primary" @click="submit">退出</el-button></el-header>
<script>
export default {
name: 'App',
methods: {
submit() {
// 向上级组件发送一个redirec事件,事件参数为'/login.json'
this.$emit('redirect', '/login.json');
},
},
};
</script>
修改App.vue
:
<template>
<div id="app">
<component :config="view" v-bind:is="view.name" @redirect="onRedirect"/>
<trace :information="trace"/>
</div>
</template>
<script>
import Admin from './components/Admin';
import Trace from './components/Trace';
import Login from './components/Login';
export default {
name: 'App',
data() {
return {
trace: {
rows: [],
},
view: {
},
};
},
created() {
this.$addReceiver((data) => {
// 捕获调试信息
if (data.trace) this.trace = data.trace;
});
this.$nextTick(() => {
this.onRedirect();
});
},
components: {
Admin,
Trace,
Login,
},
methods: {
onRedirect(url, value = null) {
return this.$httpGet(url, value).then((response) => {
this.view = response.view;
throw new Error('route');
}).catch(() => {});
},
},
};
</script>
修改main.js
import Http from './Util/Http';
window.host = '/';
window.index = 'index.json';
// import必须置顶,require就未必了
require('./api/mock');
Vue.createUrl = url => (url || window.host + window.index);
Vue.config.productionTip = false;
前面Http.js
有个小修改
static HttpSend = (url, value = null, post = false) => {
const option = {
method: post ? 'post' : 'get',
// 这里原来用的this......
url: Http.createUrl(url),
};
if (post) {
页面跳转.PNG
现在,npm run dev
看看效果吧!