Vue.js: share funcitons and data etc each component -- Mixin

@someMixin.js

export const someMixin = {
  data() {
    return {
    

    },

  methods: {

 

  },

  computed() {

  }

 

@someComponent.vue

import { someMixin } from './someMixin';

 

export default {

 mixins: [someMixin]

}

#174

global mixin はすべてのsingle vue instance 生成時に影響が出るので注意

mixin life cycle

f:id:monteecristoo:20170826202902j:plain

Vue.js toggle css classes

  • bind single class

 

  • bind object to manage multi css classes

<script src="https://unpkg.com/vue"></script>
<div id="app">

  <div class="demo" @click="attachRed = !attachRed" :class="divClasses"> </div>

  <div class="demo"></div>

  <dv class="demo"></dv>

</div>

 

new Vue({

el: '#app',

data: { attachRed: false, },

computed: {

  divClasses: function() {

    return { red: this.attachRed, blue: !this.attachRed };

  }

}

});

 or other  way 

  • change class dynamicaly by v-model

 demo3 が2つのクラスを持てることに注意

  • dynamicaly styling with no css class

Vuex state management

f:id:monteecristoo:20170825055335p:plain

state

data をとどめておく場所。どの component からも this.$store.state.hoge からアクセス可能

 

getters

state を加工したい場合使用。同じ加工を複数の component で使用したい場合、code の duplicate を防ぐ。どの component からも this.$store.getters からアクセス可能

 

actions 

 import mapActions from 'vuex';

 

methods: {
  ...mapActions({
    loadUser: 'loadUser'

  }),

 

 

Laravel5.4 ORM + PHP Traits

ORMにfunctionを追記出来るがreusableでなく、肥大化することがあるためtraitsを使うことがある。

TraitsやORMのfunctionはmethod chainやORM向けのmethodを使用できる点で優れる。

 

@App\foo.php (ORM)

use App\Traits\Friendable;

 

class User extends Authenticatable
{

  use Notifiable;

  use Friendable;

 

 

@App\Traits\Friendable.php

<php?

namespace App\Traits;

 

trait friendable {

  public function hello {
    return "Hello World!";

   }

}

 

@web.php

Rotue::get('/hello', function() {

  return Auth::user()->hello();

}); 

 

kati #9

 

参考:

monteecristoo.hatenablog.com

blog.toshimaru.net

Vue.js within Laravel Authentication from Vue component

Laravel内に設置型のVue.js component内からLaravelのAuth::routesを使う方法

 

* vue component内にはlaravel blade template が使えないので {{ route('logout') }} 等の便利なディレクティブが使えない。

 

 

通常の {{ route('logout') }} で発行されるHTMLを見てみると…

<li>

<a href="http://YOUR HOME PAGE/logout" onclick="event.preventDefault();
document.getElementById('logout-form').submit();"><i class="fa fa-sign-out"></i>
Logout
</a>

<form id="logout-form" action="http://YOUR HOME PAGE/logout" method="POST" style="display: none;"><input type="hidden" name="_token" value="WrMYReqTjHiHSoVBbIjxdnvCVhj0y70FvQ4BdeZQ"></form>

</li>

 

token付きでPOSTしているので手動でcsrf token を設定する必要がある。

 

@Vue component

<template>

<a href="/logout" onclick="event.preventDefault();
document.getElementById('logout-form').submit();">
<i class="fa fa-sign-out"></i>
Logout
</a>
<form id="logout-form" action="/logout" method="POST" style="display: none;">
<input type="hidden" name="_token" :value="csrf_token">
</form>

</template>

<script>
var csrf_token = $('meta[name="csrf-token"]').attr('content');

export default {
  data() {
    return {
      token: csrf_token
    }
  }
}
</script>

 

参考:

monteecristoo.hatenablog.com

stackoverflow.com

Authentication Laravel with Vue.js

f:id:monteecristoo:20170819184517j:plain9

Backend

@UserController.php

/*--------------------------------------
| For Frontend Authentication |
---------------------------------------*/
public function signup(Request $request)
{
$this->validate($request, [
'name' => 'required',
'email' => 'required|email|unique:users',
'password' => 'required'
]);

$user = new User([
'name' => $request->input('name'),
'email' => $request->input('email'),
'password' => bcrypt($request->input('password'))
]);
$user->save();
return response()->json([
'message' => 'Successfully created user!'
], 201);
}
}

@api.php

/*---------------------------------------------
| For Authentication from Frontend
----------------------------------------------*/
Route::post('/user', [
'users' => 'UserController@signup'
]);

 

Frontend

http requestのheaderには、

Content-Type applicatiob/json  →→ laravel側にjsonリクエストとして認識させる

X-Requested-With XMLHttpRequest  →→ ajaxリクエストであることの表明

10

 

tokenの管理(セットアップ)

  • jwt-authを使用

composer.json

"require": {
    "tymon/jwt-auth": "0.5.*"
}

を加筆

composer update  →→ jwt-authをインストール

  • Service Provider に jwt-auth を登録

@config/app.php

'providers' => [

/*
* Package Service Providers...
*/

Tymon\JWTAuth\Providers\JWTAuthServiceProvider::class,

]

を加筆

  • aliases に jwt-auth の facade を追加

@config/app.php

'aliases' => [

'JWTAuth' => Tymon\JWTAuth\Facades\JWTAuth::class,

を加筆

  • config の編集を発効
php artisan vendor:publish --provider="Tymon\JWTAuth\Providers\JWTAuthServiceProvider"

jwt.php が生成される( jwt-auth の config ファイル)

  •  JWT Authentication Secret key の生成
php artisan jwt:generate

jwt.php

'secret' => env('JWT_SECRET', 'hoge'),

が加筆される

 

token の管理(ロジック)

public function Signin(Request $request)
{
$this->validate($request, [
'name' => 'required',
'email' => 'required|email',
'password' => 'required'
]);
$credentials = $request->only('email', 'password');
try {
  if(!$token = JWTAuth::attempt($credentials))  /* credentialのチェック */
  {
    return response()->json([
      'error' => 'Invalid Credentials!'
    ], 401);
  }
} catch(JWTException $e) {
  return response()->json([
    'error' => 'Could not create token!'
  , 500]);
}
return response()->json([
  'token' => $token  /* tokenの発行 */
], 200);
}

11

CSS position: sticky;

CSS position stickyについて

 

他のカラム等を加味しながら要素を固定したい

e.g) サイドバーと別カラムでトップメニューを固定表示したい

→ sticky

 

他の要素を加味しない

→ fixed

 

stickyを使うときはtop, left, right等の場所を指定するプロパティーと一緒に使うこと

stickyに表示したい要素を構成する最上部のelementに指定すること

fixedと入れ子で指定できない(要検証)