DAY7---如何解决页面刷新后二次加载路由?(页面刷新后,路由状态会丢失,导致需要二次加载路由。)

1.用history模式。(可以在不刷新页面的情况下更新 URL)(需要在创建 Router 实例时进行配置)

该模式下,浏览器会自动监听url的值,如果发送变化会自动发送请求。服务器端通常需要配置一个"后备"路由,将所有未匹配的 URL 都指向应用程序的入口点(通常是 index.html)。

2.加<keep-alive>包裹实现缓存

注意如果路由组件有嵌套路由,需要在嵌套的路由组件也使用 keep-alive 进行缓存。

const routes = [
  {
    path: '/user',
    component: UserLayout,
    children: [
      {
        path: '',
        component: UserList
      },
      {
        path: 'profile',
        component: UserProfile
      },
      {
        path: 'settings',
        component: UserSettings
      }
    ]
  }
]//嵌套路由示例


下面是一个使用 keep-alive 的嵌套路由示例:

<template>
  <div id="app">
    <router-view v-slot="{ Component }">
      <keep-alive>
        <component :is="Component" />
      </keep-alive>
    </router-view>
  </div>
</template>

<script>
export default {
  name: 'App'
}
</script>
在这个例子中,我们将整个 router-view 组件包裹在 keep-alive 中。这样,所有被渲染的组件都会被缓存下来。(这个栗子可以实现动态缓存组件。因为通过具名插槽来获取当前router-view中要渲染的组件,随后又在里面用keep-alive 来包裹这个要显示的组件。所以每当router-view切换里面的组件时,就会被keep-alive 包裹。实现动态缓存组件的功能。)



如果我们只想缓存某些特定的组件,可以使用 keep-alive 的 include 或 exclude 属性:

<keep-alive include="UserList,UserProfile">
  <router-view />
</keep-alive>

3.保存路由状态

组件卸载时保存路由状态,在组件重新挂载时恢复状态。可以使用 Pinia或者其他状态管理工具来实现这一功能。

// store/routeStore.js
import { defineStore } from 'pinia'

export const useRouteStore = defineStore('route', {
  state: () => ({
    routeState: null
  }),
  actions: {
    saveRouteState() {
      this.routeState = { ...this.$route }
    },
    restoreRouteState() {
      if (this.routeState) {
        this.$router.push(this.routeState)
      }
    }
  }
})
在组件中使用:

<script setup>
import { useRouteStore } from '@/store/routeStore'

const routeStore = useRouteStore()

onCreated() {
  routeStore.saveRouteState()//创建时,调用函数,存入初始的路由状态到pinia里
}

onBeforeUnmount() {
  routeStore.saveRouteState()//销毁前,调用函数,将目前对应的路由状态存入pinia里
}

onMounted() {
  routeStore.restoreRouteState()//渲染时,调用函数,获取之前的路由状态,并push到(它)
}
</script>
在这个实现中,我们使用 Pinia 创建了一个名为 useRouteStore 的 store,其中包含了保存和恢复路由状态的相关逻辑。

  • 4
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在 Day17 中,我们可以通过 Flask 框架快速搭建一个 BBS 论坛。具体步骤如下: 1. 创建 Flask 应用 ```python from flask import Flask app = Flask(__name__) ``` 2. 创建数据库 ```python from flask_sqlalchemy import SQLAlchemy app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///bbs.db' app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False db = SQLAlchemy(app) ``` 3. 创建数据库模型 ```python class User(db.Model): id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(20), unique=True, nullable=False) password = db.Column(db.String(20), nullable=False) class Post(db.Model): id = db.Column(db.Integer, primary_key=True) title = db.Column(db.String(100), nullable=False) content = db.Column(db.Text, nullable=False) user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False) ``` 4. 创建路由和视图函数 ```python @app.route('/') def index(): posts = Post.query.all() return render_template('index.html', posts=posts) @app.route('/post/<int:post_id>') def post(post_id): post = Post.query.get(post_id) return render_template('post.html', post=post) @app.route('/new_post', methods=['GET', 'POST']) def new_post(): if request.method == 'POST': title = request.form['title'] content = request.form['content'] user_id = 1 # 假设当前用户为 id 为 1 的用户 post = Post(title=title, content=content, user_id=user_id) db.session.add(post) db.session.commit() return redirect('/') return render_template('new_post.html') @app.route('/login', methods=['GET', 'POST']) def login(): if request.method == 'POST': username = request.form['username'] password = request.form['password'] user = User.query.filter_by(username=username, password=password).first() if user: session['user_id'] = user.id return redirect('/') else: flash('用户名或密码错误') return render_template('login.html') @app.route('/logout') def logout(): session.pop('user_id', None) return redirect('/') ``` 5. 创建 HTML 模板 创建 index.html、post.html、new_post.html、login.html 四个模板文件,并且使用 jinja2 模板引擎渲染数据。 6. 运行应用 ```python if __name__ == '__main__': app.run() ``` 以上就是快速搭建 BBS 论坛的主要步骤,当然在实际应用中还需要考虑更多细节问题,比如用户认证、数据校验、页面美化等。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值