knaka Tech-Blog

AI, IoT, DIYエレクトロニクス, データサイエンスについて投稿予定です。

rails5 + Vue.js , ルーティングなど SPA開発(15) #Vue.js #web #SPA

index:

概要:

前のSPA 関連で、rails5 の組合せで
vue-router で、ルーティング追加等になります。

環境

rails 5.2.2
vue.js
vue-router
webpack

参考の設定

github.com

設定など

・index.html.erb
https://github.com/kuc-arc-f/vue12_ver1/blob/master/app/views/home/index.html.erb

<div id="app">
    <navbar></navbar>
    <div class="container">
        <router-view></router-view>
    </div>
</div>

<%= javascript_pack_tag 'todo' %>


・todo.js
https://github.com/kuc-arc-f/vue12_ver1/blob/master/app/javascript/packs/todo.js

import Vue from 'vue/dist/vue.esm.js'
import Router from './router/router'
import Header from './components/header.vue'

//
var app = new Vue({
  router: Router,
  el: '#app',
  components: {
    'navbar': Header,
  }  
});

・header.vue
https://github.com/kuc-arc-f/vue12_ver1/blob/master/app/javascript/packs/components/header.vue

<template>
  <div>
    <ul id="dropdown" class="dropdown-content">
      <li><router-link to="/">Top</router-link></li>
      <li><router-link to="/about">About</router-link></li>
      <li><router-link to="/tasks">Tasks</router-link></li>
    </ul>
  </div>
</template>

・router.js : ルーティングを書きます。

https://github.com/kuc-arc-f/vue12_ver1/blob/master/app/javascript/packs/router/router.js

//
import Vue from 'vue/dist/vue.esm.js'
import VueRouter from 'vue-router'
import tasksIndex from '../components/index.vue'
import About from '../components/about.vue'
import Top from '../components/top.vue'
//import Contact from '../components/contact.vue'

Vue.use(VueRouter)

export default new VueRouter({
  mode: 'history',
  routes: [
    { path: '/', component: Top },
    { path: '/about', component: About },
    { path: '/tasks', component: tasksIndex },
  ],
})


・routes.rb : rails 側のルーティングも、書きます

https://github.com/kuc-arc-f/vue12_ver1/blob/master/config/routes.rb



関連のページ

knaka0209.hatenablog.com

rails5 + Vue.js +webpack の設定編 SPA開発(14) #Vue.js #web #SPA

index:

概要:

前のSPA 関連で、
rails5 の組合せとなります。

環境

rails 5.2.2
vue.js
webpack

windows7 です。

参考の設定

github.com


設定など

rails アプリの作成
rails new vue12 --webpack=vue


・yarn を追加しておきます。
npm install -g yarn

・vue関係の追加

yarn add axios
yarn add vue-router
yarn add vue-template-compiler
yarn add vuex
yarn add vue-eslint-parser

起動

・webpack-dev-server 起動
ruby.exe bin/webpack-dev-server

rails の起動
rails s

Vue.js(Vue-CLI 3)で、ルートのパスをデプロイ時に変更する。 SPA開発(13) #Vue.js #web #php #SPA

index:

概要:

前のSPA 関連で、
Vue-CLI 3でのデプロイ時のパスを、ルートから
変更する方法となります。
下層フォルダに、Webサービスを配置可能になりますね。

環境

Vue-CLI 3
vue.js

設定方法

vue.config.js を追加し。
npm run build すると、反映できました。
下記の、publicPath の配置フォルダを指定できます。

module.exports = {
    publicPath: '/tst/app1'
}

aws EC2で、cakephpの設置 SPA開発(12) #web #php #SPA

index:

概要:

前のSPA 関連で、
バックエンドは、aws EC2にcakephp 2 (php フレームワーク)
の設置関連となります。

フロント側は、Vue.js で、web APIを呼び出す構成を
想定した場合です。

環境

cakephp 2.10.17
php7.2
aws EC2, amazon linux 2

参考のページ

knaka0209.hatenablog.com

knaka0209.hatenablog.com

LAMP 等の、設定は
 前の記事を、参考にしています。

mysql DB, table
は事前に作成しておきます。

設定など

・cakephp2
を、
/var/www/htmlに配置します。

・cakeの書込みエラーが出る場合は、権限の追加。
chmod -R 777 app/tmp/

・AllowOverride の設定
/etc/httpd/conf/httpd.conf

<Directory "/var/www/html/apiphp1">
	AllowOverride All
</Directory>

apacheの再起動
sudo systemctl restart httpd

Vue.js(Vue-CLI 3) +cakephp +mysql SPA開発(11) #Vue.js #web #php

index:

概要:

前のSPA 関連で、
クロスドメイン構成の仕組みで、アプリ構築する事例となります。

バックエンドは、cakephp 2 (php フレームワーク)
で、mysql DBの組合せの場合です。

環境

Vue.js
Vue-CLI 3
cakephp 2.10.17
php7.1
jQuery

参考の設定

・フロント側
github.com

API
github.com


準備など

・cakephp2, ver2 を clone
https://github.com/cakephp/cakephp

・事前にDBの、作成。
表(tasks) の作成。
https://github.com/kuc-arc-f/apiphp1_ver1/blob/master/db/tasks.sql

Linux の場合、mod_rewrite エラーが出る場合
a2enmod で有効化
sudo a2enmod rewrite

rewrite の確認
ls -l /etc/apache2/mods-enabled/ | grep rewrite


・AllowOverride の設定
/etc/apache2/sites-available/000-default.conf

<Directory "/var/www/html/apiphp1">
	AllowOverride All
</Directory>

apacheの再起動
sudo systemctl restart apache2

・cakeの書込みエラーが出る場合は、権限の追加。
chmod -R 777 app/tmp/

実装など

コントローラ TasksController.php
https://github.com/kuc-arc-f/apiphp1_ver1/blob/master/app/Controller/TasksController.php

api_index

	//
	public function api_index() {
		$this->Task->recursive = 0;
	    $this->Paginator->settings = array(
			'limit' => 10 ,'order'=> array('Task.id'=>'desc')
		   );		
		$dats = $this->Paginator->paginate();
		$arr = array();
		foreach ($dats as $dat){
			$arr[] = $dat["Task"];
		}
		header('Access-Control-Allow-Origin: *');
		header('Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept');
		echo(json_encode($arr ));
		exit();
	}	

api_add

	public function api_add() {
		if ($this->request->is('post')) {
			$this->Task->create();
			$json ='';
			if ($this->Task->save($this->request->data)) {
				$json = json_encode(['title' => $this->request->data["Task"] ]);
			} else {
				$json = json_encode(['message' => 'The task could not be saved. Please, try again.' ]);
			}
			header('Access-Control-Allow-Origin: *');
			header('Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept');
			echo( $json );
			exit();
		}
	}

Vue.js 側

Index.vue
https://github.com/kuc-arc-f/vue_2_cake/blob/master/src/components/Tasks/Index.vue

import axios from 'axios'
import {Mixin} from '../../mixin'

export default {
  mixins:[Mixin],
  created () {
    this.baseUrl = this.sysConst.API_BASE;
    console.log( this.baseUrl )
    this.getTasks()
  },
  data () {
    return {
      tasks: [],
      user_id : '',
      baseUrl : ''
    }
  },
  methods: {
    getTasks() {
        var url = this.baseUrl +'tasks/api_index'
        console.log(url)
        axios.get(url)
        .then(res =>  {
            this.tasks = res.data
            console.log(res.data.length )
        })
    },
  }
}

関連のページ

knaka0209.hatenablog.com

Laravel 5 を、aws EC2 インストール編 #web #php #Laravel

index:

概要:

Laravel 5 を、aws EC2 ,Amazon Linux 2
に追加する手順等になります。

・手順に、抜けがあるかもしれませんが。
・インストール時に、メモリ不足で、composerが強制終了
 する場合が、ありましたが。回避方法は複数ありそうでしたが
 下記の手順で、インスタンス再起動後、apache ,mysqlを終了後、
 に追加すると、正常インストールできました。

環境

Amazon Linux 2
php7.2
apahce
mysql
Laravel 5.6

参考

https://docs.aws.amazon.com/ja_jp/AWSEC2/latest/UserGuide/ec2-lamp-amazon-linux-2.html

aws の、LAMP追加方法が参考になりました。
 上記の手順では、拡張モジュールが不足していましたので
 追加モジュールの対応後、インストールの手順となりました。

https://qiita.com/PKunito/items/31445d4475d4e18fe4d7

参考の設定方法

sudo yum update -y

sudo amazon-linux-extras install -y lamp-mariadb10.2-php7.2 php7.2

sudo yum install -y httpd mariadb-server

sudo systemctl start httpd

sudo systemctl enable httpd

sudo systemctl start mariadb

sudo systemctl enable mariadb


・mbstring, dom のエラーが出たので、追加モジュール対応

sudo yum install --enablerepo=remi-php72 php-mbstring php-openssl
sudo yum install php-xml

Laravel インストール

・上記の手順で、開始すると。
 メモリ不足で、composer が強制終了したので、
 ログアウト、インスタンス再起動後
 インストールした方が良いかもしれません。

LAMP系のサービスの停止( とりあえず、メモリ確保の為に停止 )

sudo systemctl stop httpd

sudo systemctl stop mariadb

・composer の追加

curl -sS https://getcomposer.org/installer | php

・インストール

php  composer.phar create-project --prefer-dist laravel/laravel spa1 "5.6.*"

apache の設定

・http.conf 、ルートの変更。

DocumentRoot "C:/xampp71/htdocs/spa1/public"


.htaccess 有効化

<Directory /var/www/spa1/public>
    AllowOverride All
</Directory>

apache を、再起動すると。Laravel のトップが表示できました。
必用なヘルパ等は、この後に追加しています。

Vue.js +php, ローカルHTMLからクロスドメイン接続版 #Vue.js #web #php

index:

概要:

前のVue.js 関連で、
クロスドメイン構成の仕組みで、アプリ構築する事例となります。

以前の, Vue-CLI +firebase 構成と似ていますが。
バックエンドは、以前の自前APIサービスで
Codeigniter3 のphp軽量フレームワーク、sqlite3
の構成となります。

・ローカルのフォルダからも、htmlをブラウザ開くと
 全ての機能が使用できる。アプリ構成としました

環境

Vue.js
php7.1
sqlite3
jQuery

参考の設定

・フロント側
github.com

API
github.com

ajaxのクロスドメイン対応

ajax で、クロスドメイン通信する場合は。通常はエラーになりますが
phpで、ヘッダ情報を追加すると回避できました。

・コントローラに追加しています。

header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept');        

実装など

・画面間のキー情報は、localStorage
で、渡しています。

・index
https://github.com/kuc-arc-f/vue3_cros_ver1/blob/master/index.html

var baseUrl = 'http://127.0.0.1/code-3/';
console.log(baseUrl)
//
var app = new Vue({
    el: '#app',
    created() {
        this.getTasks()
        var dat = exStorage.load(sysConst.STORAGE_KEY_pageId )
        //exStorage.remove(sysConst.STORAGE_KEY_pageId)
        console.log(dat[0])
    },    
    data: {
        tasks : [],
    },
    methods: {
        getTasks() {
            var url = this.conv_url('api/tasks')
            axios.get(url)
            .then(res =>  {
                this.tasks = res.data
                //console.log(res.data.length )
            })
        },
        conv_url(url) {
            return baseUrl + url
        },
        move_url(id) {
            console.log(id)
            var store = []
            store.push({ 'id' : id })            
            exStorage.save(sysConst.STORAGE_KEY_pageId , store)
            window.location.href='show.html'
//            console.log(sysConst.STORAGE_KEY_pageId)
        }
    }    
});

・show
https://github.com/kuc-arc-f/vue3_cros_ver1/blob/master/show.html

var baseUrl = 'http://127.0.0.1/code-3/';
console.log(baseUrl)
//
var app = new Vue({
    el: '#app',
    created() {
        var dat = exStorage.load(sysConst.STORAGE_KEY_pageId )
        console.log(dat.length )
        if(dat.length < 1){
            alert('表示IDの取得に失敗しました。');
        }else{
            this.task_id= dat[0].id
        }
    },    
    data: {
        item : [],
        task_id: 0,
    },
    mounted: function() {
        this.getItem();
    },    
    methods: {
        getItem() {
            var url = this.conv_url('api/tasks/show/'+ this.task_id)
            console.log(url)
            axios.get(url)
            .then(res =>  {
                this.item = res.data
//                console.log(res.data )
            })
        },
        conv_url(url) {
            return baseUrl + url
        },
    }    
});

おまけ

・netlify.com (ホスティングサービス)で、設置した場合でも
 正常に動作しました。
・バックエンドは、LAN上の APIサービスです。

f:id:knaka0209:20190504101714p:plain