20210123のvue.jsに関する記事は12件です。

【Vue.js】v-bindの記法について

v-bindにより、Vueインスタンスから、htmlに属性をセットすることができる。

<div id="app">
  <a v-bind:href="url">リンク</a>
</div>

<script>
  new Vue({
  el: '#app',
  data: {
    url: 'https://google.com'
  }
})
</script>

生成されるHTML

<div id="app">
  <a href="https://google.com">リンク</a>
</div>

v-bindは省略して記述できる。(:のみでオッケー)

<div id="app">
  <a :href="url">リンク</a>
</div>

属性を動的に指定する。([]で指定する)

<div id="app">
  <a :[attr]="url">リンク</a>
</div>

<script>
new Vue({
  el: '#app',
  data: {
    url: 'https://google.com',
    attr:'href'
  }
})
</script>

属性をオブジェクトで設定する。

<div id="app">
  <a v-bind="attrs">リンク</a>
</div>

<script>
  new Vue({
  el: '#app',
  data: {
    attrs:{
      href:'https://google.com',
      id: 10
    }
  }
})

生成されるhtml

<div id="app">
  <a href="https://google.com" id="10">リンク</a>
</div>
  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

Ruby on Rails アプリにVuetifyとFontAwesomeの導入

Vuetify導入

yarn add vuetify @fortawesome/fontawesome-free
app/javascript/packs/plugins/vuetify.js
import Vue from 'vue'
import Vuetify from 'vuetify'
import "vuetify/dist/vuetify.min.css"
import '@fortawesome/fontawesome-free/css/all.css'

Vue.use(Vuetify)
export default new Vuetify({
  icons: {
    iconfont: 'fa',
  }
})
app/javascript/packs/main.js
import vuetify from './plugins/vuetify'

document.addEventListener('DOMContentLoaded', () => {
  const app = new Vue({
    vuetify,
    render: h => h(App)
  }).$mount()
  document.body.appendChild(app.$el)
})

使用例

<v-icon>fas fa-home</v-icon>

FontAwesome導入

yarn add @fortawesome/fontawesome-svg-core @fortawesome/vue-fontawesome
app/javascript/packs/main.js
import { FontAwesomeIcon } from '@fortawesome/vue-fontawesome'
Vue.config.productionTip = false
Vue.component('FontAwesomeIcon', FontAwesomeIcon)

使用例

<FontAwesomeIcon icon="user"/>
<FontAwesomeIcon :icon="['far', 'star']"/>
<FontAwesomeIcon :icon="['fab', 'facebook']"/>
  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

[Vue.js] Cloud FunctionsとStorageで動的なSitemapを作ろう

はじめまして。
マインドツリーを使ってゆるく考察するサービスQ&Qを作っているあどにゃーです。今回はVue.jsのようなSPA(single page application)で動的ページを作ったけど、sitemapを毎回deployしないと更新できないのは面倒だって人向けのお話です。

Sitemapとは

Sitemap(サイトマップ)は、サイト全体のページ構成を地図のように一覧で記載しているページのことです。検索エンジンに構成ページを伝えて検索にひっかかるようにしてもらうために用意します。Vue.jsのようなSPAでも、静的なページだけの場合は、Sitemapをわざわざ準備しなくてもクローラは各ページをインデックス(登録)してくれます。しかし、Vue.jsでuser/:userIdのような動的なページを作っている場合、Sitemapを作って明示しておかないとインデックスしてくれない場合が多いです。:sob:

置き場の課題

Vue.jsの場合、Sitemapは/static/sitemap.xmlに置くのが一般的かなと思います。しかし、静的にsitemap.xmlを置いてしまうと、新しいページが生成された度にsitemapを更新してdeployすることになり手間がかかります。個人ブログなどでVue.jsを使っていて、新しいページの生成があまり頻繁に起きない場合はマニュアルでdeployすれば良いかもしれません。しかし、公開サービスで使っていてユーザが自由にページを生成できるような仕組みにしていると、マニュアルでSitemapを毎回deployするのはちょっと無理があります。:sob:
Q&Qでは、誰でもtree/treeIdを動的に作れる仕様になっているため、動的sitemapにしないと厳しい状況です。

環境

Vue.js
Firebase
Firestore
Cloud Functions

アプローチ

今回はCloud FunctionsとCloud Storageを使って動的Sitemapをクローラに読み込ませる方法を紹介します。アプローチとしては下記になります。
事前準備
1. 動的にsitemap.xmlを作成
2. Cloud Storageに作成したsitemap.xmlを保存
今回やる「検索クローラ対応」
1. firebaseのhostingで**/sitemap.xmlにアクセスしたらFunctions:updateSitemapに飛ばす
2. Cloud Storageからsitemap.xmlを読み込む
3. updateSitemap関数でsitemap.xmlを返す

スクリーンショット 2021-01-23 20.49.27.png

hostingでrewritesする

/sitemap.xmlにアクセスしたらupdateSitemapのFunctionsへとrewriteするようにします。

  "hosting": {
    "public": "dist",
    "ignore": [
      "firebase.json",
      "**/.*",
      "**/node_modules/**"
    ],
    "rewrites": [
      {
        "source": "**/sitemap.xml",
         "function": "updateSitemap"
      },
      {
        "source": "**",
        "destination": "/index.html"
      }
    ]
  }

注意:実際に静的なsitemap.xmlを置いてしまっているとそちらが優先されてしまいrewriteが作動しないです。
動的sitemapにするときは、静的なsitemapは削除するか、静的なsitemapと動的なsitemapの名前を別にしてください。
参考:https://firebase.google.com/docs/hosting/full-config#hosting_priority_order
1. Reserved namespaces that begin with a /__/* path segment
2. Configured redirects
3. Exact-match static content ← (rewritesより優先度高い)
4. Configured rewrites

Cloud Storageからsitemap.xmlをDownload

Cloud Storageに保存しているsitemap.xmlをCloud Functionsで取得します。
ここで注意しないといけない点はCloud functionsでは、通常のstorage API使えないのでfirebase admin用のcloud storage APIを参照する必要があります。

// 通常の書き方 ← functionsで使えない
const storageRef = admin.storage().ref().child(filePath)
// adminでの書き方 ←今回はこっち
const storageRef = admin.storage().bucket().file(filePath)

StorageからDLしてsitemapを返す

StorageからDLしてきたSitemapをString型に変換してクローラ用に返します。ここは特にハマるところはないと思います。

  const sitemap = data.toString()
  return res.status(200).send(sitemap)

updateSitemapのFunctionsを全体

全体としてはこんな感じになります。クローラが/sitemap.xmlにアクセスすると、updateSitemapに飛ばされて、updateSitemapでStorageからsitemap.xmlをDLしてきてクローラに返すっという流れになります。

import * as functions from 'firebase-functions'
import * as admin from "firebase-admin";
const storage = admin.storage()
/**
 * updateSitemap:
 *   /static/sitemap.xml 以下にアクセスした時に発火する関数
 *   静的なsitemap.xmlがあった場合、hostingはrewritesよりstatic contentsを優先するので注意
 *   firestorageから最新のsitemapファイルを入手してbotに食わす
 *
 */
export default functions.https.onRequest(async (req: any, res: any) => {
  // File pathの指定
  storageRef =  storage.bucket('test.appspot.com').file('sitemap/sitemap.xml')
  // dataの取得
  const data = await storageRef.download()
  if (!data) { return }
  // dataをStingに変換
  const sitemap = data.toString()
  if (!sitemap) { return }
  return res.status(200).send(sitemap)
})

まとめ:動的なSitemapの生成

Cloud FunctionsとCloud Storageで動的なSitemapを作りました。動的なページを本格的に作るならnuxt.jsなどのバックエンドフレームワークを入れるべきかもしれませんが、手軽にやりたいという人にはおすすめです。

https://qnqtree.com/tree/c1QRc2SUPl5jMDVfxKqY
QnQというサービスで使ってますので、よろしければみてみてください。上はJavaScriptのQQトレンドまとめ記事

  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

laravel-mixのコンパイルでSyntaxError: Unexpected token = と怒られたら

発生したエラー

laravel-mixでコンパイルしたところ下記のエラーで怒られた
触ってないファイルでsyntax errorとか言われて困った

ubuntu
# npm run dev
npm WARN npm npm does not support Node.js v10.23.1
npm WARN npm You should probably upgrade to a newer version of node as we
npm WARN npm can't make any promises that npm will work with this version.
npm WARN npm Supported releases of Node.js are the latest release of 4, 6, 7, 8, 9.
npm WARN npm You can find the latest version at https://nodejs.org/

> @ dev /var/www/vue-laravel-spa
> npm run development

npm WARN npm npm does not support Node.js v10.23.1
npm WARN npm You should probably upgrade to a newer version of node as we
npm WARN npm can't make any promises that npm will work with this version.
npm WARN npm Supported releases of Node.js are the latest release of 4, 6, 7, 8, 9.
npm WARN npm You can find the latest version at https://nodejs.org/

> @ development /var/www/vue-laravel-spa
> mix

[webpack-cli] /var/www/vue-laravel-spa/node_modules/laravel-mix/src/Mix.js:18
    static _primary = null;
                    ^

SyntaxError: Unexpected token =
    at new Script (vm.js:83:7)
    at NativeCompileCache._moduleCompile (/var/www/vue-laravel-spa/node_modules/v8-compile-cache/v8-compile-cache.js:240:18)
    at Module._compile (/var/www/vue-laravel-spa/node_modules/v8-compile-cache/v8-compile-cache.js:184:36)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)
    at Module.load (internal/modules/cjs/loader.js:653:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
    at Function.Module._load (internal/modules/cjs/loader.js:585:3)
    at Module.require (internal/modules/cjs/loader.js:692:17)
    at require (/var/www/vue-laravel-spa/node_modules/v8-compile-cache/v8-compile-cache.js:159:20)
    at module.exports (/var/www/vue-laravel-spa/node_modules/laravel-mix/setup/webpack.config.js:2:17)
npm ERR! code ELIFECYCLE
npm ERR! errno 2
npm ERR! @ development: `mix`
npm ERR! Exit status 2
npm ERR! 
npm ERR! Failed at the @ development script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /root/.npm/_logs/2021-01-23T09_26_30_393Z-debug.log
npm ERR! code ELIFECYCLE
npm ERR! errno 2
npm ERR! @ dev: `npm run development`
npm ERR! Exit status 2
npm ERR! 
npm ERR! Failed at the @ dev script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /root/.npm/_logs/2021-01-23T09_26_30_443Z-debug.log

環境

% sw_vers
ProductName:    Mac OS X
ProductVersion: 10.15.7
BuildVersion:   19H2

% docker version
Client: Docker Engine - Community
 Cloud integration: 1.0.1
 Version:           19.03.13
 API version:       1.40

# php -v
PHP 7.4.7 (cli) (built: Jun 11 2020 18:41:17) ( NTS )
Copyright (c) The PHP Group
Zend Engine v3.4.0, Copyright (c) Zend Technologies
    with Xdebug v3.0.2, Copyright (c) 2002-2021, by Derick Rethans

# php artisan -v
Laravel Framework 8.24.0

原因

ググりまくった結果こちらのサイトに辿り着いた
https://github.com/JeffreyWay/laravel-mix/issues/2570
どうやらnode.jsのバージョンを最新にすると直るらしい

対処

こちらの記事を参考に対処した
https://qiita.com/seibe/items/36cef7df85fe2cefa3ea
https://qiita.com/kiwi-bird/items/e3e551938d09282cf4ee
今回初めて知ったのだがn packageを使うことでnpmパッケージとnode.js自体のバージョン管理をしてくれるらしい
こんな便利なものがあったのか

というわけでn packageをインストールする

ubuntu
# npm install n -g  # グローバルにインストールする
npm WARN npm npm does not support Node.js v10.23.1
npm WARN npm You should probably upgrade to a newer version of node as we
npm WARN npm can't make any promises that npm will work with this version.
npm WARN npm Supported releases of Node.js are the latest release of 4, 6, 7, 8, 9.
npm WARN npm You can find the latest version at https://nodejs.org/
/usr/local/bin/n -> /usr/local/lib/node_modules/n/bin/n
+ n@7.0.0
added 1 package from 4 contributors in 0.858s

# n stable  # 最新のnodejsをインストール
  installing : node-v14.15.4
       mkdir : /usr/local/n/versions/node/14.15.4
       fetch : https://nodejs.org/dist/v14.15.4/node-v14.15.4-linux-x64.tar.xz
   installed : v14.15.4 (with npm 6.14.10)

Note: the node command changed location and the old location may be remembered in your current shell.
         old : /usr/bin/node
         new : /usr/local/bin/node
To reset the command location hash either start a new shell, or execute PATH="$PATH"

# apt purge -y nodejs npm   # aptで入れた古いnodejsとnpmを削除
Reading package lists... Done
Building dependency tree       
Reading state information... Done
The following packages were automatically installed and are no longer required:
  gyp javascript-common libbrotli1 libc-ares2 libexpat1 libjs-inherits libjs-is-typedarray libnode-dev libnode64 libpython-stdlib
  libpython2-stdlib libpython2.7-minimal libpython2.7-stdlib libreadline7 libssl-dev libuv1 libuv1-dev lsb-base mime-support nodejs-doc python
  python-minimal python-pkg-resources python2 python2-minimal python2.7 python2.7-minimal
Use 'apt autoremove' to remove them.
The following packages will be REMOVED:
  node-abbrev* node-ajv* node-ansi* node-ansi-align* node-ansi-regex* node-ansi-styles* node-ansistyles* node-aproba* node-archy*
  node-are-we-there-yet* node-asn1* node-assert-plus* node-asynckit* node-aws-sign2* node-aws4* node-balanced-match* node-bcrypt-pbkdf*
  node-bluebird* node-boxen* node-brace-expansion* node-builtin-modules* node-builtins* node-cacache* node-call-limit* node-camelcase*
  node-caseless* node-chalk* node-chownr* node-cli-boxes* node-cliui* node-clone* node-co* node-color-convert* node-color-name*
  node-combined-stream* node-concat-map* node-concat-stream* node-config-chain* node-console-control-strings* node-copy-concurrently*
  node-core-util-is* node-cross-spawn* node-cyclist* node-dashdash* node-decamelize* node-decompress-response* node-deep-extend* node-defaults*
  node-delayed-stream* node-delegates* node-detect-indent* node-detect-newline* node-duplexer3* node-duplexify* node-ecc-jsbn* node-editor*
  node-encoding* node-end-of-stream* node-errno* node-escape-string-regexp* node-execa* node-extend* node-extsprintf* node-find-up*
  node-flush-write-stream* node-forever-agent* node-form-data* node-from2* node-fs-vacuum* node-fs-write-stream-atomic* node-fs.realpath*
  node-gauge* node-get-caller-file* node-get-stream* node-getpass* node-glob* node-got* node-graceful-fs* node-gyp* node-har-schema*
  node-har-validator* node-has-flag* node-has-symbol-support-x* node-has-to-string-tag-x* node-has-unicode* node-hosted-git-info*
  node-http-signature* node-iconv-lite* node-iferr* node-import-lazy* node-imurmurhash* node-inflight* node-inherits* node-ini* node-invert-kv*
  node-is-builtin-module* node-is-npm* node-is-object* node-is-plain-obj* node-is-retry-allowed* node-is-stream* node-is-typedarray*
  node-isarray* node-isexe* node-isstream* node-isurl* node-jsbn* node-json-parse-better-errors* node-json-schema* node-json-stable-stringify*
  node-json-stringify-safe* node-jsonify* node-jsonparse* node-jsonstream* node-jsprim* node-latest-version* node-lazy-property* node-lcid*
  node-libnpx* node-locate-path* node-lockfile* node-lowercase-keys* node-lru-cache* node-mem* node-mime-types* node-mimic-fn*
  node-mimic-response* node-minimatch* node-minimist* node-mississippi* node-mkdirp* node-move-concurrently* node-mute-stream* node-node-uuid*
  node-nopt* node-normalize-package-data* node-npm-package-arg* node-npm-run-path* node-npmlog* node-oauth-sign* node-object-assign* node-once*
  node-opener* node-os-locale* node-osenv* node-p-cancelable* node-p-finally* node-p-limit* node-p-locate* node-p-timeout* node-package-json*
  node-parallel-transform* node-path-exists* node-path-is-absolute* node-path-is-inside* node-performance-now* node-prepend-http*
  node-process-nextick-args* node-promise-inflight* node-promzard* node-proto-list* node-prr* node-pump* node-pumpify* node-punycode* node-qs*
  node-qw* node-rc* node-read* node-read-package-json* node-readable-stream* node-registry-auth-token* node-registry-url* node-request*
  node-require-directory* node-require-main-filename* node-resolve-from* node-retry* node-rimraf* node-run-queue* node-safe-buffer* node-semver*
  node-semver-diff* node-set-blocking* node-sha* node-shebang-command* node-shebang-regex* node-signal-exit* node-slash* node-slide*
  node-sorted-object* node-spdx-correct* node-spdx-expression-parse* node-spdx-license-ids* node-sshpk* node-ssri* node-stream-each*
  node-stream-iterate* node-stream-shift* node-string-decoder* node-string-width* node-strip-ansi* node-strip-eof* node-strip-json-comments*
  node-supports-color* node-tar* node-term-size* node-text-table* node-through* node-through2* node-timed-out* node-tough-cookie*
  node-tunnel-agent* node-tweetnacl* node-typedarray* node-uid-number* node-unique-filename* node-unpipe* node-url-parse-lax*
  node-url-to-options* node-util-deprecate* node-uuid* node-validate-npm-package-license* node-validate-npm-package-name* node-verror*
  node-wcwidth.js* node-which* node-which-module* node-wide-align* node-widest-line* node-wrap-ansi* node-wrappy* node-write-file-atomic*
  node-xdg-basedir* node-xtend* node-y18n* node-yallist* node-yargs* node-yargs-parser* nodejs* npm*
0 upgraded, 0 newly installed, 241 to remove and 18 not upgraded.
After this operation, 16.7 MB disk space will be freed.
(Reading database ... 19266 files and directories currently installed.)
Removing npm (5.8.0+ds6-4+deb10u2) ...
Removing node-gyp (3.8.0-6) ...
Removing node-nopt (3.0.6-3) ...
Removing node-abbrev (1.1.1-1) ...
Removing node-request (2.88.1-2) ...
Removing node-har-validator (5.1.0-1) ...
Removing node-ajv (5.0.0-1) ...
Removing node-ansi (0.3.0-3) ...
Removing node-boxen (1.2.2-1) ...
Removing node-ansi-align (2.0.0-1) ...
Removing node-libnpx (10.2.0+repack-1) ...
Removing node-yargs (10.0.3-2) ...
Removing node-cliui (4.1.0-1) ...
Removing node-wrap-ansi (4.0.0-1) ...
Removing node-chalk (2.3.0-2) ...
Removing node-ansi-styles (3.2.1-1) ...
Removing node-ansistyles (0.1.3-1) ...
Removing node-npmlog (4.1.2-1) ...
Removing node-gauge (2.7.4-1) ...
Removing node-cacache (11.3.2-2) ...
Removing node-move-concurrently (1.0.1-2) ...
Removing node-archy (1.0.0-2) ...
Removing node-are-we-there-yet (1.1.4-1) ...
Removing node-http-signature (1.2.0-1) ...
Removing node-sshpk (1.13.1+dfsg-2) ...
Removing node-asn1 (0.2.3-1) ...
Removing node-dashdash (1.14.1-2) ...
Removing node-jsprim (1.4.0-1) ...
Removing node-verror (1.10.0-1) ...
Removing node-form-data (2.3.2-2) ...
Removing node-asynckit (0.4.0-2) ...
Removing node-aws-sign2 (0.7.1-1) ...
Removing node-aws4 (1.8.0-1) ...
Removing node-read-package-json (2.0.13-1) ...
Removing node-copy-concurrently (1.0.5-4) ...
Removing node-bcrypt-pbkdf (1.0.1-1) ...
Removing node-bluebird (3.5.1+dfsg2-2) ...
Removing node-normalize-package-data (2.4.0-1) ...
Removing node-is-builtin-module (2.0.0-1) ...
Removing node-builtin-modules (3.0.0-1) ...
Removing node-npm-package-arg (6.0.0-2) ...
Removing node-validate-npm-package-name (3.0.0-1) ...
Removing node-builtins (1.0.3-1) ...
Removing node-call-limit (1.1.0-1) ...
Removing node-yargs-parser (11.1.1-1+deb10u1) ...
Removing node-camelcase (5.0.0-1) ...
Removing node-caseless (0.12.0-1) ...
Removing node-tar (4.4.6+ds1-3) ...
Removing node-chownr (1.1.1-1) ...
Removing node-cli-boxes (1.0.0-1) ...
Removing node-widest-line (1.2.2-1) ...
Removing node-co (4.6.0-1) ...
Removing node-color-convert (1.9.0-3) ...
Removing node-color-name (1.1.3-1) ...
Removing node-combined-stream (1.0.7-1) ...
Removing node-mississippi (3.0.0-1) ...
Removing node-concat-stream (1.6.2-1) ...
Removing node-config-chain (1.1.11-1) ...
Removing node-console-control-strings (1.1.0-1) ...
Removing node-through2 (2.0.5-2) ...
Removing node-flush-write-stream (1.0.3-1) ...
Removing node-term-size (1.2.0+dfsg-2) ...
Removing node-os-locale (2.0.0-1) ...
Removing node-execa (0.10.0+dfsg-1) ...
Removing node-cross-spawn (5.1.0-2) ...
Removing node-parallel-transform (1.1.0-2) ...
Removing node-cyclist (1.0.1-2) ...
Removing node-decamelize (1.2.0-1) ...
Removing node-latest-version (3.1.0-1) ...
Removing node-package-json (4.0.1-1) ...
Removing node-got (7.1.0-1) ...
Removing node-decompress-response (3.3.0-1) ...
Removing node-registry-url (3.1.0-1) ...
Removing node-registry-auth-token (3.3.1-1) ...
Removing node-rc (1.1.6-2) ...
Removing node-deep-extend (0.4.1-2) ...
Removing node-delayed-stream (0.0.5-1) ...
Removing node-delegates (1.0.0-1) ...
Removing node-detect-indent (5.0.0-1) ...
Removing node-detect-newline (2.1.0-1) ...
Removing node-duplexer3 (0.1.4-4) ...
Removing node-pumpify (1.5.1-1) ...
Removing node-duplexify (3.6.1-1) ...
Removing node-ecc-jsbn (0.1.1-1) ...
Removing node-editor (1.0.0-1) ...
Removing node-encoding (0.1.12-2) ...
Removing node-stream-each (1.2.2-2) ...
Removing node-pump (3.0.0-1) ...
Removing node-end-of-stream (1.4.1-1) ...
Removing node-errno (0.1.4-1) ...
Removing node-escape-string-regexp (1.0.5-1) ...
Removing node-extend (3.0.2-1) ...
Removing node-extsprintf (1.3.0-1) ...
Removing node-find-up (2.1.0-1) ...
Removing node-forever-agent (0.6.1-1) ...
Removing node-from2 (2.3.0-1) ...
Removing node-fs-vacuum (1.2.10-2) ...
Removing node-fs-write-stream-atomic (1.0.10-4) ...
Removing node-get-caller-file (1.0.2-1) ...
Removing node-get-stream (3.0.0-1) ...
Removing node-getpass (0.1.7-1) ...
Removing node-write-file-atomic (2.3.0-1) ...
Removing node-sha (2.0.1-1) ...
Removing node-graceful-fs (4.1.11-1) ...
Removing node-har-schema (2.0.0-1) ...
Removing node-supports-color (4.4.0-2) ...
Removing node-has-flag (2.0.0-1) ...
Removing node-isurl (1.0.0-1) ...
Removing node-has-to-string-tag-x (1.4.1+dfsg-1) ...
Removing node-has-symbol-support-x (1.4.1+dfsg-1) ...
Removing node-has-unicode (2.0.1-2) ...
Removing node-hosted-git-info (2.7.1-1) ...
Removing node-iconv-lite (0.4.13-2) ...
Removing node-iferr (1.0.2-1) ...
Removing node-import-lazy (3.0.0.REALLY.2.1.0-1) ...
Removing node-unique-filename (1.1.0+ds-2) ...
Removing node-imurmurhash (0.1.4-1) ...
Removing node-ini (1.3.5-1) ...
Removing node-lcid (1.0.0-1) ...
Removing node-invert-kv (1.0.0-1) ...
Removing node-is-npm (1.0.0-1) ...
Removing node-is-object (1.0.1-1) ...
Removing node-is-plain-obj (1.1.0-1) ...
Removing node-is-retry-allowed (1.1.0-1) ...
Removing node-is-stream (1.1.0-1) ...
Removing node-is-typedarray (1.0.0-2) ...
Removing node-which (1.3.0-2) ...
Removing node-isexe (2.0.0-4) ...
Removing node-isstream (0.1.2+dfsg-1) ...
Removing node-jsbn (1.1.0-1) ...
Removing node-json-parse-better-errors (1.0.2-2) ...
Removing node-json-schema (0.2.3-1) ...
Removing node-json-stable-stringify (1.0.1-1) ...
Removing node-json-stringify-safe (5.0.1-1) ...
Removing node-jsonify (0.0.0-1) ...
Removing node-jsonstream (1.3.2-1) ...
Removing node-jsonparse (1.3.1-6) ...
Removing node-lazy-property (1.0.0-3) ...
Removing node-locate-path (2.0.0-1) ...
Removing node-lockfile (1.0.4-1) ...
Removing node-lowercase-keys (1.0.0-2) ...
Removing node-lru-cache (5.1.1-4) ...
Removing node-mem (1.1.0-1) ...
Removing node-mime-types (2.1.21-1) ...
Removing node-mimic-fn (1.1.0-1) ...
Removing node-mimic-response (1.0.0-1) ...
Removing node-minimist (1.2.0-1+deb10u1) ...
Removing node-mkdirp (0.5.1-1) ...
Removing node-promzard (0.3.0-1) ...
Removing node-read (1.0.7-1) ...
Removing node-mute-stream (0.0.8-1) ...
Removing node-node-uuid (3.3.2-2) ...
Removing node-npm-run-path (2.0.2-2) ...
Removing node-oauth-sign (0.9.0-1) ...
Removing node-object-assign (4.1.1-2) ...
Removing node-opener (1.4.3-1) ...
Removing node-osenv (0.1.5-1) ...
Removing node-p-cancelable (0.3.0-1) ...
Removing node-p-timeout (1.2.0-1) ...
Removing node-p-finally (1.0.0-2) ...
Removing node-p-locate (2.0.0-1) ...
Removing node-p-limit (1.1.0-1) ...
Removing node-path-exists (3.0.0-1) ...
Removing node-path-is-inside (1.0.2-1) ...
Removing node-performance-now (2.1.0+debian-1) ...
Removing node-url-parse-lax (1.0.0-1) ...
Removing node-prepend-http (2.0.0-1) ...
Removing node-promise-inflight (1.0.1-1) ...
Removing node-proto-list (1.2.4-1) ...
Removing node-prr (1.0.1-1) ...
Removing node-tough-cookie (2.3.4+dfsg-1) ...
Removing node-punycode (2.1.1-2) ...
Removing node-qs (6.5.2-1) ...
Removing node-qw (1.0.1-1) ...
Removing node-require-directory (2.1.1-1) ...
Removing node-require-main-filename (1.0.1-1) ...
Removing node-resolve-from (4.0.0-1) ...
Removing node-retry (0.10.1-1) ...
Removing node-tunnel-agent (0.6.1-1) ...
Removing node-semver-diff (2.1.0-2) ...
Removing node-semver (5.5.1-1) ...
Removing node-set-blocking (2.0.0-1) ...
Removing node-shebang-command (1.2.0-1) ...
Removing node-shebang-regex (2.0.0-1) ...
Removing node-signal-exit (3.0.2-1) ...
Removing node-slash (1.0.0-1) ...
Removing node-slide (1.1.6-2) ...
Removing node-sorted-object (2.0.1-1) ...
Removing node-validate-npm-package-license (3.0.1-1) ...
Removing node-spdx-correct (1.0.2-1) ...
Removing node-spdx-expression-parse (1.0.4-1) ...
Removing node-spdx-license-ids (1.2.2-1) ...
Removing node-ssri (5.2.4-2) ...
Removing node-stream-iterate (1.2.0-4) ...
Removing node-stream-shift (1.0.0-1) ...
Removing node-strip-eof (1.0.0-2) ...
Removing node-strip-json-comments (2.0.1-2) ...
Removing node-text-table (0.2.0-2) ...
Removing node-through (2.3.8-1) ...
Removing node-timed-out (4.0.1-4) ...
Removing node-tweetnacl (0.14.5+dfsg-3) ...
Removing node-typedarray (0.0.6-1) ...
Removing node-uid-number (0.0.6-1) ...
Removing node-unpipe (1.0.0-1) ...
Removing node-url-to-options (1.0.1-1) ...
Removing node-uuid (3.3.2-2) ...
Removing node-which-module (2.0.0-1) ...
Removing node-wide-align (1.1.0-1) ...
Removing node-xdg-basedir (3.0.0-1) ...
Removing node-xtend (4.0.1-2) ...
Removing node-y18n (3.2.1-2) ...
Removing node-yallist (3.0.3-1) ...
Removing node-run-queue (1.0.3-1) ...
Removing node-aproba (1.2.0-1) ...
Removing node-assert-plus (1.0.0-1) ...
Removing node-rimraf (2.6.2-1) ...
Removing node-glob (7.1.3-2) ...
Removing node-minimatch (3.0.4-3) ...
Removing node-brace-expansion (1.1.8-1) ...
Removing node-balanced-match (0.4.2-1) ...
Removing node-string-width (2.1.1-1) ...
Removing node-wcwidth.js (1.0.0-1) ...
Removing node-defaults (1.0.3-1) ...
Removing node-clone (2.1.2-1) ...
Removing node-concat-map (0.0.1-1) ...
Removing node-readable-stream (2.3.6-1) ...
Removing node-core-util-is (1.0.2-1) ...
Removing node-fs.realpath (1.0.0-1) ...
Removing node-inflight (1.0.6-1) ...
Removing node-inherits (2.0.3-1) ...
Removing node-isarray (2.0.4-1) ...
Removing node-once (1.4.0-3) ...
Removing node-path-is-absolute (1.0.0-1) ...
Removing node-process-nextick-args (2.0.0-1) ...
Removing node-string-decoder (1.2.0-1) ...
Removing node-safe-buffer (5.1.2-1) ...
Removing node-util-deprecate (1.0.2-1) ...
Removing node-wrappy (1.0.2-1) ...
Removing node-strip-ansi (4.0.0-1) ...
Removing node-ansi-regex (3.0.0-1) ...
Removing nodejs (10.23.1~dfsg-1~deb10u1) ...
(Reading database ... 14507 files and directories currently installed.)
Purging configuration files for npm (5.8.0+ds6-4+deb10u2) ...

##### 一度ログインしなおす #######

# npm run dev   # いざコンパイル

> @ dev /var/www/vue-laravel-spa
> npm run development


> @ development /var/www/vue-laravel-spa
> mix

    Additional dependencies must be installed. This will only take a moment.

    Running: npm install vue-loader@^15.9.5 --save-dev --legacy-peer-deps

npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.2.13 (node_modules/fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.2.13: wanted {"os":"darwin","arch":"any"} (current: {"os":"linux","arch":"x64"})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@2.3.1 (node_modules/chokidar/node_modules/fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@2.3.1: wanted {"os":"darwin","arch":"any"} (current: {"os":"linux","arch":"x64"})

    Finished. Please run Mix again.


# npm run dev   # againとのことなので

> @ dev /var/www/vue-laravel-spa
> npm run development


> @ development /var/www/vue-laravel-spa
> mix

99% done plugins BuildOutputPlugin



   Laravel Mix v6.0.10   


✔ Compiled Successfully in 16791ms
┌───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┬─────────┐
│                                                                                                                                  File │ Size    │
├───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┼─────────┤
│                                                                                                                            /js/app.js │ 1.4 MiB │
│                                                                                                                           css/app.css │ 179 KiB │
└───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┴─────────┘

成功しました
/public/js/app.js/public/css/app.cssが生成されました

  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

ポートフォリオ ー店舗管理システム作ってみた

初めに

バックエンドをLaravel,フロントエンドをVue.jsを用いて実装しています。
この記事ではアプリ開発の説明や工夫した点を記載したいと思います。

アプリの概要

実際に飲食店舗の従業員は活用することをイメージしながら作成した店舗管理システムです。

・店長の事務業務負荷
・実際に生じている店舗の問題点

を解決できるようにすることをコンセプトとして作成しました。
「Cafe de Drip」という喫茶店で活用されることを想定しています。

アプリURL:https://cafe-de-drip.herokuapp.com/
※ユーザー認証が必要なので閲覧できません....。

GitHub:https://github.com/Tanaka-Kizuki/Store-management-system

↓ユーザー認証後のホーム画面
Cafe de Drip ホーム画面.png

実際に店舗で起きている問題点

◉勤怠管理システム(打刻式)がなくタイムカードもしくはシステム上に手打ち
 →店長がシステム上に勤怠入力もしくは実績と入力に相違がないか確認・承認作業

◉ノートを使った共有事項の伝達
 →ノートを手書きで書く作業負荷

◉日々の発注業務
 →発注が出来る能力者が限られており、休みの日でも出勤もしくは遠隔発注

上記問題点解決策(具体的なアプリ実装・機能)

◉勤怠管理システムの導入
スクリーンショット 2021-01-23 18.03.23.png

◉掲示板形式の連絡ノート
スクリーンショット 2021-01-23 18.36.22.png

◉店舗在庫を入力することで必要数が発注される発注システム
スクリーンショット 2021-01-23 18.38.04.png

機能一覧

◉ユーザー管理登録
 ○管理者権限
 ○新規登録(管理者のみ有効)
 ○ログイン、ログアウト機能
◉勤怠管理システム
 ○出退勤
 ○休憩開始、終了
 ○出退勤時刻、休憩時間より勤務時間の算出(15分繰り上げ)
 ○ユーザーの勤怠実積照合(ログイン従業員の指定月の勤務実積表示)
 ○日次勤怠照合(指定日に勤務していた従業員、勤務時間等表示)
◉コミュニケーションノート
 ○新規作成
 ○編集
 ○削除
◉発注システム
 ○アイテムの追加、編集
 ○発注(データベース登録)
 ○発注履歴の表示

使用技術

◉フロントエンド
 ○HTML/CSS
 ○JavaScript
 ○Vue.js 4.3.1
◉バックエンド
 ○PHP 7.4.9
 ○Laravel 7.27.0
◉インフラ
 ○mysql 8.0.21

  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

Vue.js トランジションとアニメーション(自分用)

Udemy 超Vue.js 2 完全パック 155 - 181

トランジション

v-border など

子コンポーネント.vue
<template>
    <p v-border>Home</p>
</template>
  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

【Vue.js基礎第1回】環境構築・ディレクティブ

はじめに

Vue.jsの基礎について複数回に渡ってまとめていきます。今回は「環境構築」と「ディレクティブ」についてです。動作確認済みのコードも記述しています。※内容は初学者向けです。

準備

今回はCDNを用いて導入。Vueの公式ホームページより最新のCDNを取得。bodyタグの直前に記述。別のファイルにJSを記述する場合は、CDNの後に挿入する。
https://jp.vuejs.org/v2/guide/installation.html#CDN

cdn.html
<body>
<div id="app">
 //本記事ではここにVueで操作したい内容を記述
</div>
<script src="https://cdn.jsdelivr.net/npm/vue@2.6.12/dist/vue.js"></script>
<script src="app.js"></script>
</body>
</html>

new Vueでインスタンスを生成し、html内のVueを使用する場所をel要素で指定する。

vue.js
new Vue({
  el:'#app'
})

ディレクティブ

v-という接頭辞がついたVue.jsの属性のこと。DOMに対して動作を適用することができる。

参考:https://rightcode.co.jp/blog/information-technology/vue-js-introduction-directive

①v-bind

タグの属性を動的に設定できる。

v-bind:<属性の名前="属性に代入される変数名">

使用例:

v-bind.html
<div id="app">
  <a v-bind:href="url">URL</a>
</div>
v-bind.js
new Vue({
    el:'#app',
    data: {
        url : 'http://localhost'
    }
})

v-bindは省略できる。

v-bind2.html
<a :href="url">URL</a>

表示
vbind.png

②v-on

イベントのトリガーを呼び出す関数を定義する。

v-on:<イベント名>="<呼び出す関数名>"

参考:v-onの後ろに置くことができるDOMイベント
https://developer.mozilla.org/ja/docs/Web/Events

引数を取らない時

メソッド名に()は不要。あっても問題ない。

v-on.html
<div id="app">
  <p>カウント数:{{ counter }}</p>
  <button v-on:click="countUp">カウントアップ</button>
</div>
v-on.js
new Vue({
    el:'#app',
    data: {
        counter: 0
    },
    methods:{
        countUp:function(){
            this.counter += 1;
        }
    }
})

引数をとる時

引数を複数渡すこともできる。下記例は引数に10を渡して10倍ずつカウントアップしている。

v-on2.html
<div id="app">
  <p>カウント数:{{ counter }}</p>
  <button v-on:click="countUp(10)">カウントアップ</button>
</div>
v-on2.js
new Vue({
    el:'#app',
    data: {
        counter: 0
    },
    methods:{
        countUp:function(times){
            this.counter += 1 * times;
        }
    }
})

v-on:は@で省略可能

v-on3.html
<div id="app">
  <p>カウント数:{{ counter }}</p>
  <button @click="countUp">カウントアップ</button>
</div>

表示
スクリーンショット 2021-01-23 10.07.38.png

③v-model

双方向バインディングを可能にするため、テキストボックスの文字列を変更すると、連動してのVue側の値も変更される。

双方向バインディング:
スクリプト側から値の設定とブラウザからの入力のどちらからでも双方向で値を更新できる仕組み。
 ブラウザから入力 <==> 変数 a <==> JavaScriptから更新
参考:https://ameblo.jp/forefrontier/entry-12330323176.html
※バインディングは結びつけるの意。

使用例:

v-model.html
<div id="app">
  <input type="text" v-model="message">
  <h1>{{ message }}</h1>
</div>
v-model.js
new Vue({
    el:'#app',
    data: {
    message: 'Hello、JS!'
  }
})

出力
スクリーンショット 2021-01-23 10.59.09.png

入力フォームに「Hello、JS!」と入力すると、データが変更される↓
スクリーンショット 2021-01-23 10.59.24.png

④v-if

条件に応じてhtml要素を動的に変更する。

使用例:FizzBuzzをカウントアップで表示

<div id="app">
  <p v-if="FizzBuzz">FizzBuzz</p>
  <p v-else-if="Fizz">Fizz</p>
  <p v-else-if="Buzz">Buzz</p>
  <p v-else>{{ count }}</p>
  <button @click="countUp">カウントアップ</button>
</div>
new Vue({
    el:'#app',
    data: {
        count:1
    },
    methods: {
        countUp:function(){
            this.count += 1;
        }
    },
    computed: {
        FizzBuzz: function() {
            return this.count %3 == 0 && this.count % 5 == 0; 
        },
        Fizz : function() {
            return this.count %3 == 0;
        },
        Buzz : function() {
            return this.count %5 == 0;
        }
    }
})

表示「FizzBuzz」
fizzbuzz 2021-01-23 18.19.40.png
表示「Fizz」
fizz.png
表示「else」
else 2021-01-23 18.18.15.png

⑤v-for

オブジェクトや配列の中身を表示する。

v-for = "<配列やオブジェクト名> in <配列やオブジェクトの複数形>"

使用例:

v-for.html
<div id="app">
  //配列の場合
  <ul>
    <li v-for="color in colors">{{ color }}</li>  
  </ul>
  //オブジェクトの場合
  <ul>
    <li v-for="value in object">{{ value }}</li>
  </ul>
</div>
v-for.js
new Vue({
    el:'#app',
    data: {
        colors: ['','',''],
        objects: {
          name: 'Evan You',
          age: 35,
          birthplace:'China'
        }
    }
})

表示
v-for.png
スクリーンショット 2021-01-24 7.37.21.png

オブジェクトや配列は引数をとることができる。

v-for2.js
<div id="app">
  <ul>
    <li v-for="(value,key,index) in objects">({{ index }}){{ key }}-{{value }}</li>
  </ul>
</div>

スクリーンショット 2021-01-24 7.51.54.png

最後に

Vueのディレクティブについてまとめました。複数回に渡ってVueの基礎をまとめていきます。
(もしこの記事に誤りがありましたらご教授いただけると幸いです。)

  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

CDNでGoogle Mapを描く

概要

  • vueでgoogle mapを描く時のパッケージであるvue2-google-mapはGASでwebページを作成する時は使えません。
  • @googlemaps/js-api-loaderというパッケージはCDNが提供されているので、これを使いました。

開発の背景

  • 勤務先ではGsuitesを使って、製品検索ページやら取引先へのメール配信やらにGASを使ったWebアプリケーションを作成しています。
  • GASでWebアプリを作る場合、フロント側はHTML形式で書く必要があります。普通vueやnuxtでフロントページを作る場合はwebpackでインストールしますが、GASのHTMLではwebpackは使えません。そのため、パッケージツールはCDNを頼ることになります
  • Vueでgoogle mapを使うときはvue2-google-mapを使うのが一般的だと思うのですが、2021年1月現在vue2-google-mapのCDNは提供されていません。https://github.com/Jeson-gk/vue2-google-maps/blob/master/API.md
  • そこで、vue2-google-mapを使うことなく、別のパッケージを使用しました。

設計

  • こちらの記事を参考にしています。

https://qiita.com/terrierscript/items/9a9dda5a5ca5b3293d48

構成

  • いつものnuxt風な構成にしています

layouts/default.html

<!DOCTYPE html>
<html>
<head>
  <base target="_top">
  <?!= include("config") ?>
</head>
<body>
  <?!= include("store/index") ?>
  <?!= include("components/ChildMarker") ?>
  <?!= include("components/MapLoader") ?>

  <?!= include("pages/index") ?>

  <div id="app"></div>

  <script>
    new Vue({
      vuetify: vuetify,
      store: store,
      render: h => h(index)
    }).$mount("#app")
  </script>

</body>
</html>

pages/index.html

<script type="text/x-template" id="index">
  <v-app>
    <v-sheet>
          <map-loader>
            <template slot-scope="scopeProps">
              <child-marker
                v-for="(marker, i) in markers" :key="i"
                :position="marker" :google="scopeProps.google" :map="scopeProps.map"/>
            </template>
          </map-loader>

    </v-sheet>
  </v-app>
</script>

<script>
  const index = {
    template: "#index",
    components: {
      "MapLoader":MapLoader,"ChildMarker":ChildMarker
    },
    data() {
      return {
        loadeds: ["お待ち下さい"],
        markers:[
          {"lat":35.6432027,"lng":139.6729435},
          {"lat":35.5279833,"lng":139.6989209},
          {"lat":35.6563623,"lng":139.7215211},
          {"lat":35.6167531,"lng":139.5469376},
          {"lat":35.6950961,"lng":139.5037899}
        ]
      }
    },
  }
</script>

components/MapLoader.html

  • ここが今回のミソです。
  • templateにv-ifを書くことで、googleオブジェクトとmapオブジェクトが作られないと子コンポーネントであるChildMarkerが作られない仕組みです。
  • mountedの内容はExampleに書いてあるとおりに作りました
<script type="text/x-template" id="map-loader">
  <div>
    <div ref="map" style="width:800px;height:500px"></div> <!-- point 1 -->
    <template v-if="!!this.google && !!this.map">
      <slot :google="google" :map="map"></slot>
    </template>
  </div>
</script>

//google mapを使うためのCDN
<script src="https://unpkg.com/@googlemaps/js-api-loader@1.0.0/dist/index.min.js"></script>

<script>
  const MapLoader = {
    template:"#map-loader",
    data(){return{
      google:null,
      map:null
    }},
//mountedでgoogleオブジェクトとmapオブジェクトを作成する
    mounted(){
      let self = this
      const {Loader} = google.maps.plugins.loader
      const loader = new Loader({apiKey: "API-KEY"})
      const mapOption = {
        center:{lat:35,lng:135},
        zoom:8
      }

      loader
        .load()
        .then(()=> {
          self.google = google
          self.map = new google.maps.Map(self.$refs.map,mapOption)
        })
        .catch(e=>{
          console.log(e)
        })
    },
  }
</script>

components/ChildMarker.html

  • ここのgoogleオブジェクトとmapオブジェクトは親であるMapLoaderコンポーネントから引き継いでます
<script>
const ChildMarker =  {
  template:"<div></div>",
  props:{
    google:Object,map:Object,
    position:Object //{lat:Number,lng:Number}
  },
  data(){return{
    marker:null
  }},
  mounted(){
    const { Marker } = this.google.maps
    this.marker = new Marker({
      position: this.position,
      map: this.map,
      title: "Child marker!"
    })
  }
}
</script>
  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

firebaseのCloud Firestoreの指定のドキュメント内の既に登録済みのフィールドを、上書きせずに新たに値を追加する場合(※ionic-vueで開発中)

例えば
既に登録済みの、ドキュメントのidが
addedPetIdで、既に登録済みのフィールド

petProfile: { 
  petName: "ペットの名前"
}

petProfile: { 
  petName: "ペットの名前",
  petAvatar: photoUrl 
}

このような形で
petAvatar: photoUrlを新たに追加したい場合

.setを使って、下記のようにすれば追加できる。

async addPetProfileAvatar(addedPetId, photoUrl) {
    const user = this.getUser();
    return await this.db
      .collection(`users/${user.uid}/pets`)
      .doc(`${addedPetId}`)
      .set(
        {
          petProfile: { petAvatar: photoUrl },
        },
        { merge: true } // ←これが大事
      )
      .then()
      .catch(function(error) {
        console.error("Error adding document: ", error);
      });
  }

ポイントは
{ merge: true }を追加してるところ。
これは

新しいデータを既存のドキュメントに統合するオプション

だそうです。
これがないと他の値は消されて、新たに追加された値だけ入った状態で上書きされます。

参考:
https://firebase.google.com/docs/firestore/manage-data/add-data

  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

Vue.js インスタンス生成後に実行したいメソッド

目的

開発中にページ読み込み時に実行したいメソッドがあった。 最初、window:onload を使ってみたがうまくいかなかった。

うまくいかない例

以下のコードではページ読み込み時にメソッドは実行されているのだが、コンソールで確認したところtitle に値が入っていなかった。

  <div id="app">
    <h1>{{ title }}</h1>
  </div>
var app = new Vue({
  el: '#app',
  data: {
    title: ''
  },
  method: {
    window:onload = function() {
    this.title = 'Welcome to my page!'
    }
  }
})

解決策

method ではなくcreatedを使う

サンプルコード

  <div id="app">
    <h1>{{ title }}</h1>
  </div>
var app = new Vue({
  el: '#app',
  data: {
    title: ''
  },
  created: function() {
    this.title = 'Welcome to my page!'
  }
})

参考記事

https://jp.vuejs.org/v2/guide/instance.html

  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

え、まだエラー処理を一括管理していないの?

まずは謝ります。

タイトルで煽ってしまい申し訳ありません。

ところで皆さん、まずは下記のエラーメッセージをご覧ください!

NavigationDuplicated: Avoided redundant navigation to current location

vue-routerを使っている方は、一度は遭遇しているであろうこのエラー。

意味は、「同じページに遷移できないよ!」と言う意味です。

まずは、このエラーの回避策をお教えします。

this.$router.push('/').catch(() => {})

たったcatch(() => {})を付けるだけでエラーが出なくなります!

これでエラーを解決した気にならずにもうちょっと我慢して見て下さい。

では、大規模な開発になった場合、いちいちcatch(() => {})を付けるとなると面倒ですよね???

そこで、出てくるのがerrorHandlerというモジュールです!

これは、Vue特有のエラーを検知してくれる優れものです。

これは、同じようなエラーメッセージが何度も出てる場合に有効です。

使い方としては、エラーメッセージごとに処理を分けて使うといった感じです。

それでは使い方を見てみましょう!

main.jsにて以下のように関数の宣言を行います。

main.js
Vue.config.errorHandler = function (error) {
  //処理
}

※注意 アロー関数にするとエラーが起きます!!!

次に、今回のエラーを例に処理を書いていきます。

main.js
Vue.config.errorHandler = function (error) {
  if (error.name === 'NavigationDuplicated') {
    // routerで遷移する時、同じページに遷移しようとすると起こるエラーを回避
    return
  }
}

このようにして、エラーメッセージを表示させることなく処理を終えることができます!

これはめちゃくちゃ使えるのでぜひ皆さんも使ってみてください!!!

以上、「え、まだエラー処理を一括管理していないの?」でした!

良かったら、LGTM、コメントお願いします。

また、何か間違っていることがあればご指摘頂けると幸いです。

他にも初心者さん向けに記事を投稿しているので、時間があれば他の記事も見て下さい!!

Thank you for reading

  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

Vue.jsでページごとにhead,meta,titleを変える方法

皆さん、すべてのページでタイトルを同じにすると検索に引っかかりにくいってご存じですか?

他にも、サイトを作る際にパンくずリストを作っておくと、Googleロボットが認識しやすいだとか。

あまりSEOには詳しくないのですが、ここらへんの基礎知識には対応させた方が良いと考えているので、今回はタイトルの通り、ページごとにhead,meta,titleを変えていくパッケージをご紹介したいと思います。

その名もvue-headです!

説明はこの辺にしておいて、解説していきます。

パッケージのインストール

まずはvue-headをインストールします。

npm i vue-head --save

パッケージをインポート

次に、main.jsにて以下のように記述します。

main.js
import Vue from 'vue'
import VueHead from 'vue-head'

Vue.use(VueHead)

そしたら、後はコンポーネントにて好きなように設定していくだけ!

App.vue
<script>
export default{
  head: {
    title: {
      inner: 'ザエモニア',
      separater: ' | ',
      complement: '会員登録'
    },
    // グーグルリキャプチャのAPI取得
    script: [
      {
        type: 'text/javascript',
        src: 'https://www.google.com/recaptcha/api.js?render=' + process.env.VUE_APP_SITE_KEY,
        async: true
      }
    ]
  },
}
</script>

ただし、ここで注意してほしいのがscriptタグはnuxt.jsvue-routerでページ遷移する際にここで読み込まれたスクリプトファイルがそのまま残ってしまいます。

画面自体に影響がなければ良いのですが、例えば「Google reCAPTCHA」では画面右下にロゴマークが出てしまうなど邪魔になる場合があります。

その時は、window.location.hrefなどを設定することで、この問題を解消することができます。

以下にその例を挙げます。

App.vue
<script>
export default{
  beforeRouteLeave(to, from, next) {
      window.location.href = to.path
  }
}
</script>

このようにすることで、スクリプトタグを次のページに持ち込まないようにしました。

ただ、このやり方はいかがなものかなと思います。

恐らくやり方としては適切な形ではないので、悪魔で参考程度に知っておいてください。

他のやり方を知っている方は、ぜひコメント欄にてご教示お願いします。

以上、「Vue.jsでページごとにhead,meta,titleを変える方法」でした!

良かったら、LGTM、コメントお願いします。

また、何か間違っていることがあればご指摘頂けると幸いです。

他にも初心者さん向けに記事を投稿しているので、時間があれば他の記事も見て下さい!!

Thank you for reading

  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む