Vue單頁(yè)應(yīng)用的跳轉(zhuǎn),大部分使用Vue-router。要理解Vue-router的原理,首先要會(huì)Vue自帶的<component>元素。
<component>的用法很簡(jiǎn)單,只要對(duì)其 is 特性進(jìn)行動(dòng)態(tài)綁定,<component>動(dòng)態(tài)切換成多個(gè)組件。
下面我們來(lái)實(shí)現(xiàn)這樣一個(gè)功能:
結(jié)構(gòu).PNG
核心的東西是兩個(gè)頁(yè)面根據(jù)實(shí)際相互跳轉(zhuǎn),而且不需要刷新頁(yè)面。
管理頁(yè)面的框架,前面已經(jīng)實(shí)現(xiàn),下面實(shí)現(xiàn)一個(gè)登錄頁(yè)面框架。
在components目錄下新建Login.vue。
為了說(shuō)清楚事情,只實(shí)現(xiàn)一個(gè)按鈕
<template>
<div class="login">
<div><el-button type="primary" @click="submit">登錄</el-button></div>
</div>
</template>
<script>
export default {
methods: {
submit() {
// 向上級(jí)組件發(fā)送一個(gè)redirec事件,事件參數(shù)為'/index.json'
this.$emit('redirect', '/index.json');
},
},
};
</script>
<style scoped>
.login {
display: flex;
flex: 1;
background-color: dimgrey;
}
</style>
Admin組件也相應(yīng)的修改下
<el-header height="80px"><el-button type="primary" @click="submit">退出</el-button></el-header>
<script>
export default {
name: 'App',
methods: {
submit() {
// 向上級(jí)組件發(fā)送一個(gè)redirec事件,事件參數(shù)為'/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) => {
// 捕獲調(diào)試信息
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有個(gè)小修改
static HttpSend = (url, value = null, post = false) => {
const option = {
method: post ? 'post' : 'get',
// 這里原來(lái)用的this......
url: Http.createUrl(url),
};
if (post) {
頁(yè)面跳轉(zhuǎn).PNG
現(xiàn)在,npm run dev看看效果吧!