Привет! Для внесения указанных изменений в проект на Laravel + Vue.js 3, можно воспользоваться следующим подходом. Ниже представлены примерные патчи в стиле git для каждого из пунктов. Пожалуйста, адаптируйте их под структуру вашего проекта.
1. Изменение хэша страницы для открытия конкретного профиля
Файлы:
routes/web.php
app/Http/Controllers/ProfileController.php
resources/js/router/index.js
resources/js/components/Profile.vue
Патч:
diff --git a/routes/web.php b/routes/web.php
index 1234567..89abcde 100644
--- a/routes/web.php
+++ b/routes/web.php
@@ -10,6 +10,7 @@ Route::get('/', function () {
return view('welcome');
});
+Route::get('/profile/{hash}', [ProfileController::class, 'show'])->name('profile.show');
diff --git a/app/Http/Controllers/ProfileController.php b/app/Http/Controllers/ProfileController.php
index 1234567..89abcde 100644
--- a/app/Http/Controllers/ProfileController.php
+++ b/app/Http/Controllers/ProfileController.php
@@ -1,6 +1,15 @@
<?php
namespace App\Http\Controllers;
+use Illuminate\Http\Request;
+use App\Models\Profile;
class ProfileController extends Controller
{
+ public function show($hash, Request $request)
+ {
+ $profile = Profile::where('hash', $hash)->firstOrFail();
+ return view('profile.show', compact('profile'));
+ }
+
+ // API для получения профиля
+ public function getProfile($hash)
+ {
+ return Profile::where('hash', $hash)->firstOrFail();
+ }
}
diff --git a/resources/js/router/index.js b/resources/js/router/index.js
index 1234567..89abcde 100644
--- a/resources/js/router/index.js
+++ b/resources/js/router/index.js
@@ -5,6 +5,7 @@ import Home from '../views/Home.vue'
const routes = [
{
+ path: '/profile/:hash',
+ name: 'Profile',
+ component: () => import('../components/Profile.vue'),
+ props: true
+ },
{
path: '/',
name: 'Home',
diff --git a/resources/js/components/Profile.vue b/resources/js/components/Profile.vue
index 1234567..89abcde 100644
--- a/resources/js/components/Profile.vue
+++ b/resources/js/components/Profile.vue
@@ -1,5 +1,6 @@
<template>
<div class="profile">
+ <h1>{{ profile.name }}</h1>
<img :src="profile.avatar" alt="Avatar">
<p>{{ profile.description }}</p>
</div>
</template>
@@ -7,7 +8,7 @@ export default {
props: ['hash'],
data() {
return {
- profile: {}
+ profile: null
}
},
created() {
- this.fetchProfile();
+ this.fetchProfile(this.hash);
},
methods: {
fetchProfile(hash) {
axios.get(`/api/profile/${hash}`)
.then(response => {
- this.profile = response.data;
+ this.profile = response.data;
})
.catch(error => {
console.error(error);
2. Создание и управление сессией при входе
Файлы:
app/Http/Controllers/ProfileController.php
resources/js/store/index.js (если используете Vuex или другой state manager)
resources/js/components/Home.vue (или другой компонент входа)
Патч:
diff --git a/app/Http/Controllers/ProfileController.php b/app/Http/Controllers/ProfileController.php
index 89abcde..fghijkl 100644
--- a/app/Http/Controllers/ProfileController.php
+++ b/app/Http/Controllers/ProfileController.php
@@ -1,15 +1,30 @@
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Profile;
class ProfileController extends Controller
{
public function show($hash, Request $request)
{
$profile = Profile::where('hash', $hash)->firstOrFail();
return view('profile.show', compact('profile'));
}
+ public function getProfile($hash, Request $request)
+ {
+ if (!$request->session()->has('profiles_shown')) {
+ $request->session()->put('profiles_shown', []);
+ }
+
+ $profilesShown = $request->session()->get('profiles_shown');
+ $profile = Profile::where('hash', $hash)->first();
+
+ if (!$profile) {
+ return response()->json(['message' => 'Profile not found'], 404);
+ }
+
+ if (in_array($profile->id, $profilesShown)) {
+ return response()->json(['message' => 'No more profiles'], 200);
+ }
+
+ $request->session()->push('profiles_shown', $profile->id);
+ return response()->json($profile);
+ }
}
diff --git a/routes/api.php b/routes/api.php
index 1234567..89abcde 100644
--- a/routes/api.php
+++ b/routes/api.php
@@ -10,6 +10,7 @@ Route::middleware('auth:api')->get('/user', function (Request $request) {
});
-Route::get('/profiles/{hash}', [ProfileController::class, 'getProfile']);
+Route::get('/profiles/{hash}', [ProfileController::class, 'getProfile'])->middleware('session');
diff --git a/resources/js/components/Home.vue b/resources/js/components/Home.vue
index 1234567..89abcde 100644
--- a/resources/js/components/Home.vue
+++ b/resources/js/components/Home.vue
@@ -20,6 +20,15 @@ export default {
methods: {
startSession() {
axios.post('/api/start-session')
+ .then(response => {
+ this.$store.commit('setSession', true);
+ })
+ .catch(error => {
+ console.error(error);
+ });
},
checkProfiles() {
axios.get('/api/profiles')
.then(response => {
diff --git a/resources/js/store/index.js b/resources/js/store/index.js
index 1234567..89abcde 100644
--- a/resources/js/store/index.js
+++ b/resources/js/store/index.js
@@ -1,5 +1,12 @@
import { createStore } from 'vuex'
export default createStore({
state: {
+ session: false,
+ profilesShown: []
},
mutations: {
+ setSession(state, status) {
+ state.session = status;
+ },
+ addProfileShown(state, profileId) {
+ state.profilesShown.push(profileId);
+ }
},
actions: {
},
3. Очистка выдачи от ненужных данных (XHR) и защита от прямых ссылок
Файлы:
app/Http/Controllers/ProfileController.php
resources/js/components/Profile.vue
- Политики доступа (optional)
Патч:
diff --git a/app/Http/Controllers/ProfileController.php b/app/Http/Controllers/ProfileController.php
index fghijkl..mnopqrstu 100644
--- a/app/Http/Controllers/ProfileController.php
+++ b/app/Http/Controllers/ProfileController.php
@@ -30,7 +30,7 @@ class ProfileController extends Controller
if (in_array($profile->id, $profilesShown)) {
return response()->json(['message' => 'No more profiles'], 200);
}
- return response()->json($profile);
+ // Возвращаем только необходимые данные
+ return response()->json([
+ 'id' => $profile->id,
+ 'name' => $profile->name,
+ 'avatar' => $profile->avatar,
+ 'description' => $profile->description,
+ // Добавьте другие необходимые поля
+ ]);
}
}
diff --git a/resources/js/components/Profile.vue b/resources/js/components/Profile.vue
index 89abcde..fghijkl 100644
--- a/resources/js/components/Profile.vue
+++ b/resources/js/components/Profile.vue
@@ -1,10 +1,10 @@
<template>
<div class="profile">
<h1>{{ profile.name }}</h1>
- <img :src="profile.avatar" alt="Avatar">
+ <img :src="profile.avatar" alt="Avatar" loading="lazy" class="img-fluid">
<p>{{ profile.description }}</p>
</div>
</template>
<script>
export default {
props: ['hash'],
data() {
return {
- profile: {}
+ profile: null
}
},
created() {
this.fetchProfile(this.hash);
},
methods: {
fetchProfile(hash) {
axios.get(`/api/profiles/${hash}`)
.then(response => {
- this.profile = response.data;
+ if(response.data.id){
+ this.profile = response.data;
+ this.$store.commit('addProfileShown', response.data.id);
+ } else {
+ this.profile = { message: response.data.message };
+ }
})
.catch(error => {
console.error(error);
4. Улучшение визуальных шаблонов с использованием Cloud и подключение Bootstrap
Файлы:
package.json
resources/js/main.js
resources/sass/app.scss (или другой основной SCSS/CSS файл)
resources/js/components/*.vue
Патч:
diff --git a/package.json b/package.json
index 1234567..89abcde 100644
--- a/package.json
+++ b/package.json
@@ -5,6 +5,7 @@
"dependencies": {
"axios": "^0.21",
"vue": "^3.0.0",
+ "bootstrap": "^5.3.0",
// другие зависимости
},
"devDependencies": {
// dev зависимости
diff --git a/resources/js/main.js b/resources/js/main.js
index 1234567..89abcde 100644
--- a/resources/js/main.js
+++ b/resources/js/main.js
@@ -1,5 +1,6 @@
import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
+import 'bootstrap/dist/css/bootstrap.min.css'
import store from './store'
createApp(App)
diff --git a/resources/sass/app.scss b/resources/sass/app.scss
index 1234567..89abcde 100644
--- a/resources/sass/app.scss
+++ b/resources/sass/app.scss
@@ -1,3 +1,4 @@
@import '~bootstrap/scss/bootstrap';
// Ваши дополнительные стили
Использование Cloud Service для изображений (на примере Cloudinary):
diff --git a/resources/js/components/Profile.vue b/resources/js/components/Profile.vue
index fghijkl..mnopqrstu 100644
--- a/resources/js/components/Profile.vue
+++ b/resources/js/components/Profile.vue
@@ -1,10 +1,12 @@
<template>
<div class="profile">
<h1>{{ profile.name }}</h1>
- <img :src="profile.avatar" alt="Avatar" loading="lazy" class="img-fluid">
+ <img :src="cloudinaryUrl(profile.avatar)" alt="Avatar" loading="lazy" class="img-fluid">
<p>{{ profile.description }}</p>
</div>
</template>
<script>
export default {
props: ['hash'],
+ methods: {
+ cloudinaryUrl(imagePath) {
+ return `https://res.cloudinary.com/YOUR_CLOUD_NAME/image/upload/${imagePath}`;
+ }
+ },
data() {
return {
profile: null
}
5. Оптимизация с помощью PageSpeed для достижения 90+ на мобильных и ПК
Файлы:
vite.config.js или webpack.mix.js (в зависимости от используемой системы сборки)
- Компоненты Vue для ленивой загрузки изображений
resources/views/layouts/app.blade.php
Патч:
diff --git a/vite.config.js b/vite.config.js
index 1234567..89abcde 100644
--- a/vite.config.js
+++ b/vite.config.js
@@ -1,5 +1,10 @@
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
+
+import { terser } from "rollup-plugin-terser";
export default defineConfig({
plugins: [
vue(),
+ terser()
],
build: {
// настройки
}
})
diff --git a/resources/js/components/Profile.vue b/resources/js/components/Profile.vue
index mnopqrstu..vwxyz1234 100644
--- a/resources/js/components/Profile.vue
+++ b/resources/js/components/Profile.vue
@@ -1,10 +1,12 @@
<template>
<div class="profile">
<h1>{{ profile.name }}</h1>
- <img :src="cloudinaryUrl(profile.avatar)" alt="Avatar" loading="lazy" class="img-fluid">
+ <img
+ :src="cloudinaryUrl(profile.avatar)"
+ alt="Avatar"
+ loading="lazy"
+ class="img-fluid"
+ v-lazy="cloudinaryUrl(profile.avatar)"
+ >
<p>{{ profile.description }}</p>
</div>
</template>
<script>
export default {
props: ['hash'],
methods: {
cloudinaryUrl(imagePath) {
return `https://res.cloudinary.com/YOUR_CLOUD_NAME/image/upload/${imagePath}`;
}
},
data() {
return {
profile: null
}
},
created() {
this.fetchProfile(this.hash);
},
methods: {
fetchProfile(hash) {
axios.get(`/api/profiles/${hash}`)
.then(response => {
if(response.data.id){
this.profile = response.data;
this.$store.commit('addProfileShown', response.data.id);
} else {
this.profile = { message: response.data.message };
}
})
.catch(error => {
console.error(error);
});
}
}
}
diff --git a/resources/views/layouts/app.blade.php b/resources/views/layouts/app.blade.php
index 1234567..89abcde 100644
--- a/resources/views/layouts/app.blade.php
+++ b/resources/views/layouts/app.blade.php
@@ -10,6 +10,9 @@
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
+ <link rel="preconnect" href="https://res.cloudinary.com">
+ <link rel="preload" as="style" href="{{ mix('css/app.css') }}">
+ <link rel="stylesheet" href="{{ mix('css/app.css') }}" media="print" onload="this.media='all'">
<title>OnlyGirls</title>
@vite('resources/js/main.js')
</head>
Дополнительные рекомендации:
-
Минификация и сжатие: Убедитесь, что CSS и JS файлы минимизированы. Vite и Laravel Mix по умолчанию это делают в production режиме.
-
Lazy Loading для изображений: Используйте loading="lazy" для всех изображений.
-
Кэширование: Настройте кэширование статических ресурсов на сервере (например, используя Cache-Control заголовки).
-
Оптимизация изображений: Используйте сжатые форматы изображений, такие как WebP, через Cloudinary.
-
Использование CDN: Размещайте статические ресурсы (CSS, JS, изображения) на CDN для уменьшения времени загрузки.
-
Удаление неиспользуемого кода: Проверьте свой CSS и JS на наличие неиспользуемых частей и удалите их.
Заключение
Приведенные выше изменения являются общими примерами и могут потребовать адаптации под конкретную структуру вашего проекта. Рекомендуется тестировать каждое изменение по отдельности, чтобы убедиться в его корректной работе. Также полезно использовать инструменты для анализа производительности, такие как Lighthouse внутри Chrome DevTools, для детального понимания, какие области требуют оптимизации.
Если у вас возникнут дополнительные вопросы или потребуется помощь с конкретными участками кода, не стесняйтесь обращаться!