Files
ClassContent/历届学生/front-end-team-10/每天课程/2023-03-21/vueRouter.html
2024-09-27 02:06:13 +08:00

183 lines
4.4 KiB
HTML

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>VueRouter</title>
<style>
.router-link-exact-active {
color: red;
}
.slide-fade-enter-active {
transition: all .3s ease;
}
.slide-fade-leave-active {
transition: all .8s cubic-bezier(1.0, 0.5, 0.8, 1.0);
}
.slide-fade-enter,
.slide-fade-leave-to
/* .slide-fade-leave-active for below version 2.1.8 */
{
transform: translateX(10px);
opacity: 0;
}
</style>
</head>
<body>
<div id="app">
<h1>Hello App!</h1>
<p>
<router-link to="/">首页</router-link>
<router-link to="/car">购物车</router-link>
<router-link to="/my">我的</router-link>
</p>
<transition name="slide-fade">
<router-view></router-view>
</transition>
</div>
</body>
<script src="https://unpkg.com/vue@2/dist/vue.js"></script>
<script src="https://unpkg.com/vue-router@3/dist/vue-router.js"></script>
<script>
const Home = {
template: `
<div class="home">
<ul>
<li v-for="item,index in newList"
@click="enterInfo(item.id)"
:key="index">
{{ item.title }}
</li>
</ul>
</div>
`,
data() {
return {
newList: [
{ id: 1, title: '新闻1' },
{ id: 2, title: '新闻2' },
{ id: 3, title: '新闻3' },
]
}
},
methods: {
enterInfo(id) {
this.$router.push({
name: 'info',
query: { page: 2, id: id }
})
}
}
}
const Info = {
template: `
<div class="info">详情</div>
`,
data() {
return {
id: null
}
},
created() {
this.id = this.$route.query.id
this.getData();
},
methods: {
async getData() {
console.log("使用参数:", this.id, " 发送ajax请求获取数据");
}
}
}
const My = {
template: `
<div class="my">我的</div>
`
}
const Car = {
template: `
<div class="car">购物车</div>
`
}
const Login = {
template: `
<div class="login" @click="login">
登录页面
</div>
`,
methods: {
async login() {
localStorage.setItem("token", "wjdhfbiwebv")
if (this.$route.query.hasOwnProperty("source")) {
this.$router.replace({ path: this.$route.query.source })
} else {
this.$router.replace({ path: "/" })
}
}
}
}
// my
const routes = [
{ path: '/', name: 'home', component: Home, meta: { isLogin: false } },
{ path: '/info', name: 'info', component: Info, meta: { isLogin: false } },
{ path: '/my', name: 'my', component: My, meta: { isLogin: true } },
{ path: '/car', name: 'car', component: Car, meta: { isLogin: true } },
{
path: '/login', name: 'login', component: Login, meta: { isLogin: false },
beforeEnter: (to, from, next) => {
console.log(to);
if (localStorage.getItem("token") != null) {
router.back()
} else {
next()
}
}
},
]
const router = new VueRouter({
// mode: 'history',
routes
});
router.beforeEach((to, from, next) => {
if (to.meta.isLogin) {
if (localStorage.getItem("token") != null) {
next()
} else {
next({
path: '/login',
query: {
source: to.fullPath
}
})
}
} else {
next()
}
})
const app = new Vue({
el: '#app',
router
})
</script>
</html>