20220113のvue.jsに関する記事は5件です。

Laravel + Vue.js でVuexを使えるようにする

経緯 踏切発車でVuexを入れたけど使い方よくわからない。 試行錯誤で無駄な時間を費やしたのでここに記す。 環境 Laravel 6系 (APIとして使用) Vue.js 2系 Docker 前提:vue導入済み シナリオ ログインユーザー情報取得を想定 /api/userを叩くとログインユーザーの情報(id, name)のjsonが返ってくる。 取得したユーザー情報を表示する。 準備 Vuexのインストール $ npm install vuex /app/resources/js配下にstore.jsを追加 /app/resources/js/store.js import axios from 'axios'; import Vue from 'vue'; import Vuex from 'vuex'; Vue.use(Vuex); const state = { user: [] } const mutations = { getUser(state) { axios.get('apiのURL') .then(res => { state.user = res.data; }).catch(err => { console.log(err.response); }); } } const getters = { getUsername(state) { return state.user.name; } } const actions = { getUserAction(ctx) { ctx.commit('getUser'); } } export default new Vuex.Store({ state, mutations, getters, actions }); /app/resources/js/app.jsに以下を追記 /app/resources/js/app.js import Vue from 'vue'; import store from './store'; // 追記 import ExampleComponent from './components/ExampleComponent'; /** * 省略 */ const app = new Vue({ el: '#app', store, // 追記 components: { ExampleComponent, } }); 呼び出し 以下コンポーネントで呼び出すとき /app/resources/js/component/ExampleComponent.vue <template> <!-- 省略 --> <p>{{ this.$store.getters.getUsername }}</p> ・・・ ① <!-- 省略 --> </template> <script> export default { created() { this.$store.dispatch('getUserAction'); // ・・・ ② } } </script> ① - ゲッターでユーザー名を取得する。 ② - DOM作成前にイベント発火(mounted()だと表示が遅れて微妙なのでcreated()を使用している) 多分これで動く。
  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

Firebase hostingする際のエラー対処法

私がFirebaseでホスティングする際にエラーが出て詰まりかけた部分を解説します。 ホスティングまでの流れ まずはvue cliでプロジェクトを作成します。 vue create プロジェクト名 その後firebase-toolsをインストールします。 $ npm install -g firebase-tools firebase-toolsのバージョンが変更してるとエラーが出るので、 firebase logout firebase login これで一度エラーで詰まりました。 firebase コンソールにてプロジェクトを作成します。 firebase SDKにてコードをコピペし、main.jsに貼り付けます。 // Import the functions you need from the SDKs you need import { initializeApp } from "firebase/app"; import { getAnalytics } from "firebase/analytics"; // TODO: Add SDKs for Firebase products that you want to use // https://firebase.google.com/docs/web/setup#available-libraries // Your web app's Firebase configuration // For Firebase JS SDK v7.20.0 and later, measurementId is optional const firebaseConfig = { apiKey: "", authDomain: "", projectId: "", storageBucket: "", messagingSenderId: "", appId: "", measurementId: "" }; // Initialize Firebase const app = initializeApp(firebaseConfig); getAnalytics(app); キーを隠す ここでfirebaseConfigのデータは盗まれると大変なので、.enbなどを使用し、キーをネットに上げないようにしましょう。 ビルド アプリをビルドできる状態にし、 npm run build Firebaseの初期化 $ firebase init hosting ???????? ???? ???????? ???????? ???????? ??? ?????? ???????? ?? ?? ?? ?? ?? ?? ?? ?? ?? ?? ?? ?????? ?? ???????? ?????? ???????? ????????? ?????? ?????? ?? ?? ?? ?? ?? ?? ?? ?? ?? ?? ?? ?? ???? ?? ?? ???????? ???????? ?? ?? ?????? ???????? You're about to initialize a Firebase project in this directory: <フォルダ名> === Project Setup First, let's associate this project directory with a Firebase project. You can create multiple project aliases by running firebase use --add, but for now we'll just set up a default project. ? Select a default Firebase project for this directory: <Firebase のプロジェクト名> (<Firebase のプロジェクト名>) === Hosting Setup Your public directory is the folder (relative to your project directory) that will contain Hosting assets to be uploaded with firebase deploy. If you have a build process for your assets, use your build's output directory. ? What do you want to use as your public directory? dist ? Configure as a single-page app (rewrite all urls to /index.html)? No ✔ Wrote dist/404.html ? File dist/index.html already exists. Overwrite? No i Skipping write of dist/index.html i Writing configuration info to firebase.json... i Writing project information to .firebaserc... ✔ Firebase initialization complete! この質問は超大切なので、しっかり全部理解しましょう。 適当にやると詰みます ちなみにfirebase initでもできます。その際はhostingをスペースキーを押して選択しましょう。 ? Select a default Firebase project for this directory: <Firebase のプロジェクト名> (<Firebase のプロジェクト名>) この質問ですが、firebaseで紐づけるプロジェクトを選択します。 exist a project みたいなのが出てくるので選ぶ→ちゃんと自分がさっき作ったプロジェクトにする ? What do you want to use as your public directory? dist これは初期設定だとpublicになってしまい、 Welcome Firebase Hosting Setup Complete というデモサイトが作られてしまうので、必ずdistを選んでください。 私はなぜかdistすらデモサイトになってしまい、ここをdocsにすれば解決しました。 ? Configure as a single-page app (rewrite all urls to /index.html)? ここはシングルページで良いのでY ? File dist/index.html already exists. Overwrite? No ここはYにしてしまうとまたデモサイトが作られてしまうので、絶対にN あとはgithubに自動であげますか?みたいなこと聞かれますが、Nでいいです。 ここまで来ればあとは ''' $firebase serve ''' でちゃんとサイトがみれるかローカルで確認してから $firebase deploy これで完成です。 お疲れ様でした。
  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

【Vue】「error '__VUE_SSR_CONTEXT__' is not defined」の対処

エラー内容 "npm run serve"実行時に以下エラーが発生 Module Error (from ./node_modules/@vue/cli-plugin-eslint/node_modules/eslint-loader/index.js): D:\111_VueProject\sample-project\dist\sample-project.esm.js 46:19 error '__VUE_SSR_CONTEXT__' is not defined no-undef 対処 「package.json」の"esintConfig.extends"に"vue"を追加 { ...略 "eslintConfig": { "root": true, "env": { "node": true }, "extends": [ "vue", // 追加 "plugin:vue/essential", "eslint:recommended" ], "parserOptions": { "parser": "babel-eslint" }, "rules": {} }, ...略 }
  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

Nuxt.jsのstoreで他のモジュールのstateやmutationsを使用する方法

はじめに Nuxt.js storeをモジュールで使用するときに別のモジュールのmutationsやらstateを利用したくなって調べたのでメモを残します。 目次 AモジュールでBモジュールの値を参照する(state) Aモジュールから別モジュールのMutationsを使用 参考文献 AモジュールでBモジュールの値を参照する(state) 別のモジュールのstateを参照するパターン rootStateを使用 // AモジュールからBモジュールを参照 export const actions = { add ({ rootState }, hoge) { const bMosule = rootState.b.bState this.$axios.$patch(url+ 'post/' + selectedBook.id, { post: { // 送る値 } }) .then((response) => { // レスポンス addにrootStateでrootを読み込ませてroot経由でBモジュールの値を参照します。 直接Bモジュールを読み込むことはできないが、rootを経由すると参照可能になる。 × A → B.state ○ A → root → B.state Aモジュールから別モジュールのMutationsを使用 別モジュールのMutationsを使用 commitの第3引数に {root: true} を使用 ① rootのMutationsを使用 // index.jsのalertを使える commit('alert', true, { root: true }) 第2引数にはいつも通り渡したい値をセットします。 今回の場合はrootのMutationsであるalertを使用しています。 ② BモジュールのMutationsを使用 // BモジュールのbAlertMutationsを使える commit('B/bAlert', true, { root: true }) root経由でBモジュールのMutationsを使用できます。 参考文献 https://www.lancard.com/blog/2019/04/04/vuex_call_other_module_method/ Nuxt.js公式 モジュール Nuxt.js: storeモジュールから別のstoreモジュールのstateを参照する方法
  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

【Vue.js】非同期コンポーネントの関数を親から呼ぶ

非同期コンポーネントの読み込みフラグを立てた直後に$refs['my-modal'].showModal()やmyModalRef.value.showModal()で呼んでも「そんなテンプレート参照無いんだけど!」って怒られたのでその対応です。 ※"my-modal"は任意のref属性です 前提 Vue3のCompositionAPIを使用します。 コンポーネントを非同期(defineAsyncComponent)で読み込みます。 Vue.js 非同期コンポーネント nextTickは? nextTickは非同期コンポーネントの読み込み完了まで待機していないようです(要検証)。 //isAsyncModalRef.value = true; <- v-if=trueによる非同期コンポーネント一回限りの読み込み nextTick(()=>{ console.log(myModalRef.value); //->null myModalRef.value?.showModal();//呼ばれない }); 解決方法 初回に限りwatchでテンプレート属性を監視して呼びます。2回目以降はmyModalRefに値が入っているのでそのまま呼ぶことができます。 Vue.js テンプレート参照の監視 /*setup関数内*/ const myModalRef = ref(null); function _loadedModal(){ //console.log(myModalRef.value); myModalRef.value?.showModal(); } watch(myModalRef,(newVal,oldVal)=>{ if(!oldVal)_loadedModal(); },{ flush: 'post' }); return{ "my-modal":myModalRef, showMyModal(){ //isAsyncModalRef.value = true; <-非同期コンポーネント読み込み用フラグ _loadedModal(); //初回は呼んでもオプショナルチェーンで無視される } }
  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む