Vue 메타가 업데이트를 가져오지 않음
페이지를 때 ★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★」vue-meta
는 새로운 페이지 값으로 갱신되지 않습니다.
코드
app.js
import VueMeta from 'vue-meta'
Vue.use(VueMeta, {
refreshOnceOnNavigation: true
})
App.vue
컴포넌트주요 컴포넌트)
export default {
metaInfo() {
return {
title: process.env.MIX_APP_NAME,
titleTemplate: `%s | ${process.env.MIX_APP_NAME}`,
meta: [
{ name: "robots", content: "index,follow" },
{
vmid: "description",
name: "description",
content:
"..........",
},
// and many more....
],
}
}
}
post.vue
컴포넌트
export default {
name: "singePost",
data() {
return {
post: "",
};
},
metaInfo() {
return {
title: this.post.name, // not receiving data
meta: [
{
vmid: "description",
name: "description",
content: this.post.metas[0].description, // not receiving data
},
// others......
],
}
},
mounted() {
this.getPost();
},
methods: {
getPost() {
axios
.get("/api/articles/" + this.$route.params.slug, {
headers: {
Authorization: localStorage.getItem("access_token"),
},
})
.then((response) => {
this.post = response.data.data;
})
.catch((error) => {
//....
});
},
},
감 잡히는 게 없어요?
갱신하다
이 질문을 게시할 때 업데이트되지 않는 것에 대한 것이었고, 몇 가지 조사를 하고 코드를 가지고 놀다가 vue-meta가 업데이트된다는 것을 알게 되었습니다.그러나 늦게 소셜 네트워크 웹사이트와 SEO 체커가 내 URL을 올바르게 검색할 수 없게 됩니다.
명확화
- Vue-meta가 업데이트되지만 늦게 업데이트됨
- 이 최신 업데이트로 인해 공유 및 검증 중인 시간 링크까지 SEO가 표시되지 않습니다.
My full meta tags code
metaInfo() {
return {
title: this.post.name,
meta: [
{
vmid: "keyword",
name: "keyword",
content: this.post.metas[0].tags,
},
{
vmid: "description",
name: "description",
content: this.post.metas[0].description,
},
// Open Graph / Facebook
{ vmid: "og:type", name: "og:type", content: "website" },
{
vmid: "og:url",
name: "og:url",
content: process.env.MIX_APP_URL + this.$router.currentRoute.fullPath,
},
{
vmid: "og:site_name",
name: "og:site_name",
content: `"${process.env.MIX_APP_NAME}"`,
},
{
vmid: "og:title",
name: "og:title",
content: this.post.name,
},
{
vmid: "og:description",
name: "og:description",
content: this.post.metas[0].description,
},
{
vmid: "og:image",
name: "og:image",
content: this.post.imagebig,
},
// Twitter
{
vmid: "twitter:card",
name: "twitter:card",
content: "summary",
},
{
vmid: "twitter:author",
name: "twitter:author",
content: "@xxxxxx",
},
{
vmid: "twitter:site",
name: "twitter:site",
content: "@xxxxxx",
},
{
vmid: "twitter:creator",
name: "twitter:creator",
content: "@xxxxxx",
},
{
vmid: "twitter:url",
name: "twitter:url",
content: process.env.MIX_APP_URL + this.$router.currentRoute.fullPath,
},
{
vmid: "twitter:title",
name: "twitter:title",
content: this.post.name,
},
{
vmid: "twitter:description",
name: "twitter:description",
content: this.post.metas[0].description,
},
{
vmid: "twitter:image",
name: "twitter:image",
content: this.post.imagebig,
},
],
};
},
추가의
최근에 기사를 읽었는데, JavaScript를 기반으로 한 vue-meta(일반적으로 Vue) 로드는 캐시되지 않기 때문에 FB나 Twitter 등에서 공유할 때 링크 세부사항을 볼 수 없습니다.
거기서 제안된 솔루션은 Nuxt를 사용하여 메타 데이터 서버 측을 반환하는 것이었습니다.
문의사항
- 위의 #1이 얼마나 맞는지는 모르겠지만 가능성은 있다.
- 제 앱은 일반적으로 Nuxt를 사용하지 않지만, npm 패키지를 설치했을 뿐이므로 시도해 볼 가치가 있을지도 모릅니다(Nuxt를 사용한 적이 없기 때문에, 만약 그렇다면, 그 답변에 조금 더 자세한 내용을 포함시켜 주시면 감사하겠습니다).
Vue는 JS를 사용합니다. 때, 의 ㅇㅇㅇㅇㅇㅇ는index.html
에는 콘텐츠가 없습니다.실행 시 콘텐츠를 생성하는 JS만 있습니다.VueMeta에도 동일하게 적용됩니다.문제는 링크(FB, Twitter 등)를 공유할 때 링크된 페이지를 자체 봇(기본적으로 크롤러)을 사용하여 다운로드하고 내부에서 JS를 실행하지 않고 콘텐츠를 분석한다는 것입니다.그래서 VueMeta에 의해 생성된 메타는 보이지 않습니다.
이에 대한 유일한 해결책은 JS를 실행하지 않고 모든 중요한 정보가 포함된 완전(또는 부분적으로) 사전 렌더링된 페이지를 제공하는 것입니다.
Vue 서버 측 렌더링을 사용하는 것도 한 가지 방법입니다.당연히 Nuxt와 같은 프레임워크는 바로 Vue 서버 측 렌더링을 사용합니다.
일반적으로 다음 두 가지 맛이 있습니다.
SSR - 페이지는 클라이언트(또는 봇)가 요청하는 시점에 렌더링됩니다.대부분의 경우 노드 서버를 실행해야 합니다(Vue SSR는 JS에 구현되어 있기 때문입니다).그 대표적인 예가 Nuxt.js입니다.
SSG - 서버 측 생성.페이지는 빌드 시 모든 HTML을 포함하여 생성됩니다.브라우저 서버에 로드하면 HTML + 모든 JS/CSS가 반환되지만 로드되면 동일한 Vue SPA가 반환됩니다.CDN 또는 Netlify와 같은 정적 호스팅 서비스에서 호스트할 수 있도록 노드 서버가 필요하지 않습니다.Vue World의 예로는 Gridsome, VuePress, Nuxt도 가능합니다.
주의: 예를 들어 헤드리스 크롬/테이어 또는 https://prerender.io/과 같은 서비스를 사용하는 다른 방법이 있습니다.
핵스트
앞서 말한 것처럼 Nuxt는 훌륭하지만 앱의 구조(파일 기반 라우팅), 데이터 취득 방법 등에 대해서는 매우 자기 의견을 가지고 있습니다.따라서 Nuxt로 전환하는 것은 완전한 앱 개서를 의미합니다.또한 자체(호스팅)의 결과를 초래하는 노드 서버를 실행해야 합니다.
하지만 제가 보기에 당신은 이미 서버를 사용하고 있는 것 같습니다.- Laravel.따라서 메타 렌더링을 Larabel에서 직접 구현하는 것이 가장 좋습니다.
업데이트: Laravel에서 Vue SSR를 직접 실행할 수 있을 것 같습니다.
당신의 추측은 옳습니다.저도 얼마 전에 이 같은 문제에 대한 해결책을 찾기 위해 꽤 많은 시간을 보냈습니다.내가 생각해낸 것은 다음과 같다.
- 사용하다
vue-meta
(JavaScript) - 서버측 솔루션을 실장합니다(Laravel 패키지를 사용).
이미 유사한 구현이 있기 때문에 옵션1은 명확해야 합니다.
옵션 2의 경우 다음과 같이 접근합니다.
라라벨 신청용으로 이 패키지를 골랐습니다.설치 및 등록이 용이합니다.Laravel이나 같은 기능을 하는 다른 프레임워크 및 언어용 패키지가 많이 있을 것입니다.
끝에 루트를 했습니다( 「 」 「 」 「 」 「 」 「 」 。
web.php
모든 프런트 엔드 루트 요구를 캐치하는 Laravel)을 사용하고 있는 경우:
Route::get('/{any}', 'IndexController@index')->where('any', '.*');
»IndexController
먼저 크롤러에서 온 요청인지 확인합니다.이치하다여기 일람이 있습니다.
<?php
declare(strict_types=1);
namespace App\Http\Controllers;
use Butschster\Head\Facades\Meta;
use Butschster\Head\Packages\Entities\OpenGraphPackage;
class IndexController extends Controller
{
const CRAWLERS = [
'Mozilla/5.0 (Linux; Android 6.0.1; Nexus 5X Build/MMB29P) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.96 Mobile Safari/537.36 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)',
'Mozilla/5.0 (iPhone; CPU iPhone OS 9_1 like Mac OS X) AppleWebKit/601.1.46 (KHTML, like Gecko) Version/9.0 Mobile/13B143 Safari/601.1 (compatible; AdsBot-Google-Mobile; +http://www.google.com/mobile/adsbot.html)',
'Mozilla/5.0 AppleWebKit/537.36 (KHTML, like Gecko; compatible; Googlebot/2.1; +http://www.google.com/bot.html) Safari/537.36',
'Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)',
'Mozilla/5.0 (compatible; bingbot/2.0; +http://www.bing.com/bingbot.htm)',
'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/534+ (KHTML, like Gecko) BingPreview/1.0b',
'Mozilla/5.0 (iPhone; CPU iPhone OS 7_0 like Mac OS X) AppleWebKit/537.51.1 (KHTML, like Gecko) Version/7.0 Mobile/11A465 Safari/9537.53 (compatible; bingbot/2.0; +http://www.bing.com/bingbot.htm)',
'Googlebot-Image/1.0',
'Mediapartners-Google',
'facebookexternalhit/1.1 (+http://www.facebook.com/externalhit_uatext.php)',
'facebookexternalhit/1.1',
'Twitterbot/1.0',
'TelegramBot (like TwitterBot)',
];
public function index()
{
if ($this->isACrawler()) {
$this->applyMetaTags();
return view('layouts.crawler');
}
return view('layouts.index');
}
public function isACrawler()
{
if (in_array(request()->userAgent(), self::CRAWLERS)) {
return true;
}
return false;
}
private function applyMetaTags()
{
// Here you can check the request and apply the tags accordingly
// e.g.
// preg_match("/articles\/[0-9]+/i", request()->path(), $url)
// preg_match("/[0-9]+/i", $url[0], $id);
// $article = Article::find($id);
//
// Meta::prependTitle($article->name)
// ->addMeta('description', ['content' => $article->description]);
//
// $og = new OpenGraphPackage('some_name');
//
// $og->setType('Website')
// ->setSiteName('Your website')
// ->setTitle($article->name)
// ->setUrl(request()->fullUrl())
// ->setDescription($article->description);
//
// if ($article->picture) {
// $og->addImage(asset($article->picture));
// }
//
// Meta::registerPackage($og);
}
}
그리고 마지막으로, 나는 단지 이 템플릿만을 만들었습니다.head
섹션(크롤러가 관심을 가지는 것은 html의 유일한 부분)과 메타 태그를 적용합니다.
<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
@meta_tags
<link rel="shortcut icon" href="{{ asset('favicon.ico') }}">
</head>
</html>
경고:
- 요청별로 메타 태그를 커스터마이즈해야 합니다.
- 크롤러 목록을 관리해야 합니다
이점:
- 심플하고 코드를 크게 변경할 필요가 없습니다.
- 빠르고 가벼운 HTML을 크롤러에 반환합니다.
- 백엔드를 완전히 제어할 수 있으며 약간의 조정으로 유지보수가 가능한 솔루션을 구현할 수 있습니다.
이게 도움이 됐으면 좋겠네요!뭔가 불명확한 점이 있으면 알려주세요.
메타 태그를 처리하려면 서버 사이드 렌더링을 구현해야 합니다.왜냐하면 거의 모든 크롤러가 Javascript 프로세스를 지원하지 않기 때문입니다.
다음은 PHP - Larabel의 예입니다.
아시다시피 vue.js는 1페이지 어플리케이션입니다.루트 페이지 하나에서 렌더링할 때마다
따라서 larabel의 경우 루트를 그대로 설정하고 태그 배열이 포함된 인덱스 페이지를 반환할 때마다 해당 페이지를 뷰에 렌더링합니다(인덱스 페이지).
- 라라벨 라우팅
<?php
use Illuminate\Support\Facades\Route;
Route::get('users/{id}', 'UserController@show');
Route::get('posts/{id}', function () {
$tags = [
'og:app_id' => '4549589748545',
'og:image' => 'image.jpg',
'og:description' => 'Testing'
];
return view('index', compact('tags'));
});
Route::get('/{any}', function () {
$tags = [
'description' => 'Testing',
'keywords' => 'Testing, Hello world',
];
return view('index', compact('tags'));
})->where('any', '.*');
?>
- 컨트롤러
<?php
use App\Http\Controllers\Controller;
use App\Models\User;
class UserController extends Controller
{
public function show(User $user)
{
$tags = [
'og:app_id' => '4549589748545',
'og:image' => 'image.jpg',
'og:description' => 'Testing'
];
return view('index', compact('tags'));
}
}
?>
- 색인 페이지
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
@foreach($tags as $key => $value)
<meta property="{{$key}}" content="{{$value}}">
@endforeach
</head>
<body id="app">
<script type="text/javascript" src="{{ asset('js/app.js') }}"></script>
</body>
</html>
정적 태그를 삽입하도록 웹 팩을 구성할 수 있습니다.
vue-cli 3은 웹 팩 구성 파일을 추상화하므로(실행 시 생성됨) 이를 구성하려면 vue.config.config.config를 프로젝트 루트에 추가해야 합니다(vue.config.config.config.config.config.config가 없는 경우, 일반적으로는 그렇지 않습니다).
예를 들어 다음과 같습니다.
// vue.config.js
module.exports = {
configureWebpack: {
output: {
publicPath: '/static/'
},
plugins: [
new HtmlWebpackPlugin(),
new HtmlWebpackTagsPlugin(
{tags: ['a.js', 'b.css'], append: true },
{metas: [{
path: 'asset/path',
attributes: {
name: 'the-meta-name'
}}]
})
]
}
}
(구체적인 출력에 대해서는 링크의 예를 참조해 주세요)
언급URL : https://stackoverflow.com/questions/65573622/vue-meta-not-getting-updates
'programing' 카테고리의 다른 글
NuxtJ를 사용하여 네이티브 Vue 앱을 만들 수 있습니까?s (0) | 2022.07.29 |
---|---|
Vuex 작업에서 Vuex getter로 매개 변수 전달 (0) | 2022.07.29 |
Vuex에서 이를 바인드한 후 콜백하는 방법 (0) | 2022.07.29 |
Vue CLI 버전을 확인하려면 어떻게 해야 합니까? (0) | 2022.07.29 |
JRebel의 대체 수단 재배포 (0) | 2022.07.29 |