LoginSignup
80
58

More than 5 years have passed since last update.

vue.js(nuxt.js) の plugin はとても便利

Last updated at Posted at 2018-12-07

概要

plugin を使うと便利なことが簡単にできます。もしもまだ手を付けてない人がいるならぜひ調べてみるとよいでしょう。
実際に実務で使った簡単な例を3つ紹介します。

  1. 閉じられたらバックアップ: 画面閉じられる前に store の内容をブラウザのローカルストレージに時間とともにバックアップする(マニアックですが、応用は効くはず)。
  2. v-view-only: ディレクティブを定義してメニューの一部を触れなくする。
  3. $imgUrl(path): 関数を用意して画像URLのドメイン切り替えを吸収する。

方法

nuxt.js の場合

plugins/beforeunload.js
// 閉じられたらバックアップ
export default ({store}) => {
  window.addEventListener('beforeunload', () => {
    // ローカルストレージに時刻をキーにしてデータを保存
    localStorage.setItem(`store-backup-${new Date().toISOString()}`, JSON.stringify(store.state))
  })   
}
plugins/view-only.js
import Vue from 'vue'

Vue.directive('view-only', {
  bind: function (el, binding, vnode) {
    el.style.pointerEvents = 'none' // タッチ系イベントの無効化
    el.style.opacity = '0.3' // デザイン薄く
  }
})
plugins/img-url.js
// $imgUrl(path)
import Vue from 'vue'

export const imgUrl = function (path) {
  if (location.host === 'localhost') { // 何らかの条件
    return `http://xxxxx${path}`
  } else {
    return `https://yyyyy${path}`
  }
}

Vue.prototype.$imgUrl = static_assets

これで以下を書けば有効化できます。

nuxt.config.js
module.exports = {
    (省略)
    plugins: [
        { src: '@/plugins/beforeunload', ssr: false },
        { src: '@/plugins/view-only' },
        { src: '@/plugins/img-url' },
    ],
    (省略)
利用可所
<template>
  <div>
    <Menu @click="clickMenu(1)" v-view-only>
    <Menu @click="clickMenu(2)">
    <Menu @click="clickMenu(3)">
    <img :src="$imgUrl('/hoge.png')">
  <div>
</template>

vue.js の場合

const MyPlugin = {}
MyPlugin.install = function (Vue) {
  // 閉じられたらバックアップ
  window.addEventListener('beforeunload', () => {
    console.log('ここでアクションできる。')
  })

  // $imgUrl(path)
  Vue.directive('view-only', {
    bind: function (el, binding, vnode) {
      el.style.pointerEvents = 'none' // タッチ系イベントの無効化
      el.style.opacity = '0.3' // デザイン薄く
    }
  })

  // $imgUrl(path)
  Vue.prototype.$imgUrl = function (path) {
    if (location.host === 'localhost') { // 何らかの条件
      return `http://xxxxx${path}`
    } else {
      return `https://yyyyy${path}`
    }
  }
}

これで以下を書けば有効化できます。

Vue.use(MyPlugin) 
利用可所
Vue.component('my-component', {
  template: `
  <div>
    <Menu @click="clickMenu(1)" v-view-only>
    <Menu @click="clickMenu(2)">
    <Menu @click="clickMenu(3)">
    <img :src="$imgUrl('/hoge.png')">
  <div>
  `
})

まとめ

以上、plugin を使えば簡単に Vue を拡張できて、再利用しやすくできる例の紹介でした!

80
58
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
80
58