Vue.js监听语言环境重获文章及ArticleController代码翻译处理咨询
提问:Vue.js中如何监听语言环境变化并重新获取文章?附PHP ArticleController代码中文注释
我正在开发一个多语言Vue.js项目,现在需要实现监听语言环境(locale)切换,一旦用户更换语言,自动重新拉取对应语言版本的文章数据。另外我手里有一段处理文章接口的PHP控制器代码,想给它加上中文注释,方便后续维护。
带中文注释的ArticleController代码(以Laravel框架为例)
<?php namespace App\Http\Controllers; use App\Models\Article; use Illuminate\Http\Request; class ArticleController extends Controller { /** * 获取指定语言的文章列表(分页) * @param Request $request 请求实例,用于获取locale参数 * @return \Illuminate\Http\JsonResponse 返回JSON格式的文章数据 */ public function index(Request $request) { // 从请求中获取locale参数,若未传则默认使用英文'en' $locale = $request->input('locale', 'en'); // 根据语言字段筛选文章,并按创建时间倒序排列,每页返回10条 $articles = Article::where('locale', $locale) ->orderBy('created_at', 'desc') ->paginate(10); // 组装成功响应,返回文章数据 return response()->json([ 'status' => 'success', 'data' => $articles ]); } /** * 获取单篇指定语言的文章详情 * @param Request $request 请求实例,用于获取locale参数 * @param int $id 文章ID * @return \Illuminate\Http\JsonResponse 返回JSON格式的文章详情 */ public function show(Request $request, $id) { // 从请求中获取locale参数,默认值为'en' $locale = $request->input('locale', 'en'); // 根据文章ID和语言字段查找文章,若不存在则抛出404异常 $article = Article::where('id', $id) ->where('locale', $locale) ->firstOrFail(); // 组装成功响应,返回文章详情 return response()->json([ 'status' => 'success', 'data' => $article ]); } }
Vue.js实现监听locale变化并重新获取文章的方案
如果你的项目使用vue-i18n做国际化,可以直接监听它的locale属性变化,触发重新请求:
export default { data() { return { articles: [], // 存储文章列表数据 currentLocale: this.$i18n.locale // 当前语言环境 } }, watch: { // 监听vue-i18n的locale变化 '$i18n.locale'(newLocale) { this.currentLocale = newLocale; this.fetchArticles(); // 语言切换时重新获取文章 } }, mounted() { // 页面初始化时先拉取一次当前语言的文章 this.fetchArticles(); }, methods: { async fetchArticles() { try { // 调用后端的文章列表接口,传入当前语言参数 const response = await this.$axios.get('/api/articles', { params: { locale: this.currentLocale } }); this.articles = response.data.data; } catch (error) { console.error('获取文章失败:', error); // 这里可以添加错误提示逻辑,比如给用户弹出提示框 } } } }
如果没有使用vue-i18n,而是自己维护locale状态,只需要把watch的目标改成你自己定义的locale变量即可,核心逻辑完全一致。
内容的提问来源于stack exchange,提问作者user6780526
相关产品推荐
相关产品推荐

