20210430のvue.jsに関する記事は14件です。

【Vue × Firestore】ボタンを発火させた際、認証ユーザーページをリロードさせる

ボタンを発火させた際、認証ユーザーページをリロードさせる mypage.vue <button @click="updateBtn" class="update-btn flex">更新</button> mypage.vue <script> import firebase from "firebase"; import Header from "@/components/header.vue"; import Vue from "vue"; ~ 省略 ~ methods: { updateBtn() { firebase .firestore() .collection("users") .doc(this.$route.params.uid) .set( { name: this.name, sex: this.sex, age: this.age, access: this.access, selfpr: this.selfpr, profession: this.profession, uploadedImage: this.uploadedImage, genre: this.genre, favMovie: this.favMovie, time: firebase.firestore.FieldValue.serverTimestamp(), }, { merge: true } ); this.$swal({ title: "内容確認", text: "この内容で投稿しますか?", icon: "info", buttons: true, dangerMode: true, }).then((willDelete) => { if (willDelete) { this.$swal("投稿しました。", { icon: "success", }); this.$router.go({ path: `/mypage/${this.$route.params.uid}`, force: true, }); //プロフィール編集されたらページをリロード } else { this.$swal("キャンセルしました。"); } }); }, ~ 省略 ~ </script> updateBtn()が押下されたらページをリロードさせるようにしてますが、 動的ルートマッチング「this.$route.params」について 上記記事でも書かせて頂いたように、this.$route.params.uidで現在のURLのパラメータを取得して 単純に/mypage/${this.$route.params.uidという形式でリロードをさせてます。 router.js { path: "/mypage/:uid", name: "Mypage", component: Mypage, meta: { requiresAuth: true }, }, mypage.vue this.$router.go({path: `/mypage/${this.$route.params.uid}`,force: true,});
  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

【Vue × Firestore】認証済みユーザー毎にプロフィール情報をHTMLに表示させる

認証済みユーザー毎にプロフィール情報をHTMLに表示させる mypage.vue <modal class="modal-inner" v-scroll-lock="open" name="edit" :width="1100" :height="740" > <div data-modal="edit" aria-expanded="true" class="vm--overlay"> <div class="vm--top-right-slot"></div> </div> <div class="modal-header flex"> <h2 class="profile-tll flex">プロフィールを編集する</h2> <hr class="separate" /> </div> <div class="modal-body"> <div class="profile-inner flex"> <div class="profile-contens flex"> <div class="profile-img-inner flex"> <img src="../assets/アイコン.jpg" width="200" height="200" class="profile-img" alt="プロフィール画像" /> <button class="profile-txt profile-update" @click="update"> プロフィール画像を編集する </button> </div> <div class="line"></div> <div class="profile-items flex"> <div class="profile-contens flex"> <input type="text" class="profile-item" placeholder="名前" v-model="name" /> </div> <div class="profile-contens flex"> <select class="profile-select" v-model="sex" :style="{ color: sex == '' ? 'gray' : 'white' }" > <option class="profile-item" value hidden>性別</option> <option v-for="sex in sexs" :value="sex.name" :key="sex.id" class="profile-item" style="color: white;" >{{ sex.name }}</option > </select> </div>           ~ 省略 ~     <button class="hide-btn flex" @click=" hide(); closeModal();">×</button> </div> <button @click="updateBtn" class="update-btn flex">更新</button> </div> </div> </modal> mypage.vue <script> import firebase from "firebase"; import Header from "@/components/header.vue"; import Vue from "vue"; ~ 省略 ~ export default { data() { return { name: "", sex: "", sexs: [{ name: "男性" }, { name: "女性" }, { name: "その他" }], age: "", ages: [ { name: "10際未満" }, { name: "10 ~ 19歳" }, ~ 省略 ~ ], access: "", accesses: [ { name: "北海道" }, { name: "青森県" }, { name: "岩手県" }, ~ 省略 ~ ], profession: "", professions: [ { name: "公務員" }, { name: "会社員" }, ~ 省略 ~ ], selfpr: "", genre: "", genres: [ { id: 0, name: "ジャンル" }, { id: 1, name: "アクション" }, { id: 2, name: "ドラマ" }, ~ 省略 ~ ], favMovie: "", uploadedImage: "", profileData: {}, open: false, }; }, components: { Header, }, methods: { // updateBtn()が押下されたら、dbインスタンスを初期化して"posts"という名前のコレクションへの参照 updateBtn() { firebase .firestore() .collection("users") .doc(this.$route.params.uid) //uidとは、routerの/mypage/:uidの[uid]のこと。 //コレクションのusersを参照して、ドキュメントのuidを参照。 .set( { name: this.name, sex: this.sex, age: this.age, access: this.access, selfpr: this.selfpr, profession: this.profession, uploadedImage: this.uploadedImage, genre: this.genre, favMovie: this.favMovie, time: firebase.firestore.FieldValue.serverTimestamp(), //サーバ側で値設定 }, { merge: true } //set()でmergeをtrueにすると、上書き。updetaと同様。 ); this.$swal({ title: "内容確認", text: "この内容で投稿しますか?", icon: "info", buttons: true, dangerMode: true, }).then((willDelete) => { if (willDelete) { this.$swal("投稿しました。", { icon: "success", }); this.$router.go({ path: `/mypage/${this.$route.params.uid}`, force: true, }); //プロフィール編集されたらページをリロード } else { this.$swal("キャンセルしました。"); } }); }, ~ 省略 ~ created() { const currentUser = firebase.auth().currentUser; if (currentUser) { firebase .firestore() .collection("users") .doc(this.$route.params.uid) .get() .then((snapshot) => { this.profileData = snapshot.data(); //全てのデータを取得して、profileDataへ代入。 // console.log(snapshot.data()); }); } }, </script> usersというコレクションを参照して、.doc(this.$route.params.uid)で現在のURLのパラメーター情報を取得。 get().then((snapshot)を使って、対象ユーザーの全データを取得して、 そのデータをthis.profileData = snapshot.data();でthis.profileDataへ代入してます。 profileDataへはJSON形式で格納されるようにしてます。 router.js { path: "/mypage/:uid", name: "Mypage", component: Mypage, meta: { requiresAuth: true }, }, mypage.vue export default { data() { return { profileData: {}, //JSON形式で格納。 }; created() { const currentUser = firebase.auth().currentUser; if (currentUser) { firebase .firestore() .collection("users") .doc(this.$route.params.uid) .get() .then((snapshot) => { this.profileData = snapshot.data(); //全てのデータを取得して、profileDataへ代入。 }); } あとはthis.profileDataに格納されたデータを{{ profileData.○○ }}で取得し表示させてます。 mypage.vue <div class="profile-list"> <ul class="list-item"> <li class="list-items"> 性別: <div class="list-color">{{ profileData.sex }}</div> </li> <li class="list-items"> 年齢: <div class="list-color">{{ profileData.age }}</div> </li> <li class="list-items"> 職業: <div class="list-color">{{ profileData.profession }}</div> </li> <li class="list-items"> 居住地: <div class="list-color">{{ profileData.access }}</div> </li> <li class="list-items"> 好きな映画: <div class="list-color">{{ profileData.favMovie }}</div> </li> <li class="list-items"> 好きなジャンル: <div class="list-color">{{ profileData.genre }}</div> </li> <li class="list-items"> 自己紹介: <div class="list-color">{{ profileData.selfpr }}</div> </li> </ul> </div>
  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

【Vue × Firestore】認証済みユーザーのプロフィール情報のデータ追加・上書きについて

認証済みユーザーのプロフィール情報のデータ追加・上書きについて mypage.vue <modal class="modal-inner" v-scroll-lock="open" name="edit" :width="1100" :height="740" > <div data-modal="edit" aria-expanded="true" class="vm--overlay"> <div class="vm--top-right-slot"></div> </div> <div class="modal-header flex"> <h2 class="profile-tll flex">プロフィールを編集する</h2> <hr class="separate" /> </div> <div class="modal-body"> <div class="profile-inner flex"> <div class="profile-contens flex"> <div class="profile-img-inner flex"> <img src="../assets/アイコン.jpg" width="200" height="200" class="profile-img" alt="プロフィール画像" /> <button class="profile-txt profile-update" @click="update"> プロフィール画像を編集する </button> </div> <div class="line"></div> <div class="profile-items flex"> <div class="profile-contens flex"> <input type="text" class="profile-item" placeholder="名前" v-model="name" /> </div> <div class="profile-contens flex"> <select class="profile-select" v-model="sex" :style="{ color: sex == '' ? 'gray' : 'white' }" > <option class="profile-item" value hidden>性別</option> <option v-for="sex in sexs" :value="sex.name" :key="sex.id" class="profile-item" style="color: white;" >{{ sex.name }}</option > </select> </div>           ~ 省略 ~     <button class="hide-btn flex" @click=" hide(); closeModal();">×</button> </div> <button @click="updateBtn" class="update-btn flex">更新</button> </div> </div> </modal> mypage.vue <script> import firebase from "firebase"; import Header from "@/components/header.vue"; import Vue from "vue"; ~ 省略 ~ export default { data() { return { name: "", sex: "", sexs: [{ name: "男性" }, { name: "女性" }, { name: "その他" }], age: "", ages: [ { name: "10際未満" }, { name: "10 ~ 19歳" }, ~ 省略 ~ ], access: "", accesses: [ { name: "北海道" }, { name: "青森県" }, { name: "岩手県" }, ~ 省略 ~ ], profession: "", professions: [ { name: "公務員" }, { name: "会社員" }, ~ 省略 ~ ], selfpr: "", genre: "", genres: [ { id: 0, name: "ジャンル" }, { id: 1, name: "アクション" }, { id: 2, name: "ドラマ" }, ~ 省略 ~ ], favMovie: "", uploadedImage: "", profileData: {}, open: false, }; }, components: { Header, }, methods: { // updateBtn()が押下されたら、dbインスタンスを初期化して"posts"という名前のコレクションへの参照 updateBtn() { firebase .firestore() .collection("users") .doc(this.$route.params.uid) //uidとは、routerの/mypage/:uidの[uid]のこと。 //コレクションのusersを参照して、ドキュメントのuidを参照。 .set( { name: this.name, sex: this.sex, age: this.age, access: this.access, selfpr: this.selfpr, profession: this.profession, uploadedImage: this.uploadedImage, genre: this.genre, favMovie: this.favMovie, time: firebase.firestore.FieldValue.serverTimestamp(), //サーバ側で値設定 }, { merge: true } //set()でmergeをtrueにすると、上書き。updetaと同様。 ); this.$swal({ title: "内容確認", text: "この内容で投稿しますか?", icon: "info", buttons: true, dangerMode: true, }).then((willDelete) => { if (willDelete) { this.$swal("投稿しました。", { icon: "success", }); this.$router.go({ path: `/mypage/${this.$route.params.uid}`, force: true, }); //プロフィール編集されたらページをリロード } else { this.$swal("キャンセルしました。"); } }); }, ~ 省略 ~ created() { const currentUser = firebase.auth().currentUser; if (currentUser) { firebase .firestore() .collection("users") .doc(this.$route.params.uid) .get() .then((snapshot) => { this.profileData = snapshot.data(); //全てのデータを取得して、profileDataへ代入。 // console.log(snapshot.data()); }); } }, </script> updateBtn()が押下されたらusersというコレクションを参照して、.doc(this.$route.params.uid)で現在のURLのパラメーター情報を取得。 set()を使って、各データを追加・上書きを実行。 第2引数に{ merge: true }とすることで、データを上書きしてくれます。 router.js { path: "/mypage/:uid", name: "Mypage", component: Mypage, meta: { requiresAuth: true }, }, mypage.vue methods: { updateBtn() { firebase .firestore() .collection("users") .doc(this.$route.params.uid) .set( { name: this.name, sex: this.sex, age: this.age, access: this.access, selfpr: this.selfpr, profession: this.profession, uploadedImage: this.uploadedImage, genre: this.genre, favMovie: this.favMovie, time: firebase.firestore.FieldValue.serverTimestamp(), }, { merge: true } );
  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

【Vue × Firestore】ログイン後、ヘッダーから認証済みのマイページへ遷移させる

ログイン後、ヘッダーから認証済みのマイページへ遷移させる header.vue <li><router-link :to="`/mypage/${this.uid}`" class="header-link neon3 flash">MYPAGE</router-link></li> header.vue <script> import firebase from "firebase"; export default { ~ 省略 ~ created() { const currentUser = firebase.auth().currentUser; //現在ログインしているユーザーを取得 this.uid = currentUser.uid; firebase .firestore() .collection("users") .doc(currentUser.uid) .get(); }, ~ 省略 ~ }; </script> firebase.auth().currentUserにて現在ログインしているユーザーを取得してます。 usersというコレクションを参照して、現在ログインしているユーザー(currentUser)から「uid」を取得して get()を使ってuidデータをFirestoreから取得。 header.vue created() { const currentUser = firebase.auth().currentUser; //現在ログインしているユーザーを取得 this.uid = currentUser.uid; firebase .firestore() .collection("users") .doc(currentUser.uid) .get(); }, ページを遷移させる為に一度this.uidに 「currentUser.uid;」を格納してから ${this.uid}として対象ページに遷移させています。 header.vue <li><router-link :to="`/mypage/${this.uid}`" class="header-link neon3 flash">MYPAGE</router-link></li>
  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

【Vue × Firestore】ログイン後、認証済みのマイページに遷移させる。

ログイン後、認証済みのマイページに遷移させる。 signin.vue <template> <div> <Header /> <div class="signin flex"> <div class="signin-inner flex"> <h2>ログイン</h2> <input type="text" placeholder="Email" v-model="email" /> <input type="password" placeholder="Password" v-model="password" /> <button class="btn" @click.prevent="signIn">ログイン</button> <p> アカウントをお持ちでない方は <router-link to="/signup">こちらへ</router-link> </p> </div> </div> </div> </template> signin.vue <script> import firebase from "firebase"; import Header from "@/components/header.vue";   ~ 省略 ~ export default { name: "Signin", data() { return { email: "", password: "", }; }, components: { Header, }, methods: { signIn() { firebase .auth() .signInWithEmailAndPassword(this.email, this.password) .then((res) => { //ログイン時に取得したemailとpasswordを引数であるresに渡す。 this.$swal("ログインに成功しました。 ", { icon: "success", }); this.uid = res.user.uid; //this.uidに 「res.user.uid;」を格納 return ( firebase .firestore() .collection("users") .doc(res.user.uid) //usersのドキュメントを参照して、上記で引数として受けたresのuid取得 .get() ); }) .then(() => { this.$router.push(`/mypage/${this.uid}`); }) .catch(() => { this.$swal("ログイン情報が間違っています。", { icon: "error", }); }); }, }, }; </script> まずfirebase.auth().signInWithEmailAndPassword(this.email, this.password)で ログイン時に取得したemailとpasswordをresという引数に渡してます。 signin.vue signIn() { firebase .auth() .signInWithEmailAndPassword(this.email, this.password) .then((res) => { //ログイン時に取得したemailとpasswordを引数であるresに渡す。 this.$swal("ログインに成功しました。 ", { icon: "success", }); usersというコレクションを参照して、上記で取得したresから「uid」を取得して get()を使ってuidデータをFirestoreから取得。 signin.vue return ( firebase .firestore() .collection("users") .doc(res.user.uid) //usersのドキュメントを参照して、上記で引数として受けたresのuid取得 .get() ); ページを遷移させる為に一度this.uidに 「 res.user.uid;」を格納してから ${this.uid}として対象ページに遷移させています。 signup.vue this.uid = res.user.uid; //this.uidに 「res.user.uid;」を格納 ~ 省略 ~ .then(() => { this.$router.push(`/mypage/${this.uid}`); })
  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

【Vue × Firestore】新規登録時に取得したuidを元にマイページにページ遷移させる

新規登録時に取得したuidを元にマイページにページ遷移させる signup.vue <template> <div> <Header /> <div class="signup flex"> <div class="signup-inner flex"> <h2>新規登録</h2> <input type="text" placeholder="Username" v-model="name" /> <input type="text" placeholder="Email" v-model="email" /> <input type="password" placeholder="Password" v-model="password" /> <button class="btn-signup" @click.prevent="signUp">登録</button> <p> 既に登録済みの方は <router-link to="/signin">こちらへ</router-link> </p> </div> </div> </div> </template> signup.vue <script> import firebase from "firebase"; import Header from "@/components/header.vue";   ~ 省略 ~ export default { name: "Signup", data() { return { email: "", password: "", name: "", uid: "", }; }, components: { Header, }, methods: { signUp() { firebase .auth() .createUserWithEmailAndPassword(this.email, this.password) .then((userCredential) => { //新規登録時に取得したemailとpasswordを引数であるuserCredential(ユーザー資格情報)に渡す。 this.$swal("登録に成功しました。", { icon: "success", }); this.uid = userCredential.user.uid; //this.uidに 「userCredential.user.uid;」を格納 return firebase .firestore() .collection("users") .doc(userCredential.user.uid) //usersのドキュメントを参照して、上記で引数として受けたuserCredentialのuid取得 .set({ name: this.name, time: firebase.firestore.FieldValue.serverTimestamp(), uid: userCredential.user.uid, //各マイページにページ遷移する為にuidをfirestoreに格納 }); }) .then(() => { this.$router.push(`/mypage/${this.uid}`); //新規登録後、「/mypage/userCredential.user.uid」で該当ページに遷移 }) .catch(() => { this.$swal("登録情報が正しくありません。", { icon: "error", }); }); }, }, }; </script> まずfirebase.auth().createUserWithEmailAndPassword(this.email, this.password)で 新規登録時に取得したemailとpasswordを引数であるuserCredential(ユーザー資格情報)に渡します。 signup.vue signUp() { firebase .auth() .createUserWithEmailAndPassword(this.email, this.password) .then((userCredential) => { //新規登録時に取得したemailとpasswordを引数であるuserCredential(ユーザー資格情報)に渡す。 this.$swal("登録に成功しました。", { icon: "success", }); usersというコレクションを参照して、上記で取得したuserCredential(ユーザー資格情報)から「uid」を取得して set()を使ってuidをFirestoreにデータを追加。 signup.vue return firebase .firestore() .collection("users") .doc(userCredential.user.uid) //usersのドキュメントを参照して、上記で引数として受けたuserCredentialのuid取得 .set({ name: this.name, time: firebase.firestore.FieldValue.serverTimestamp(), uid: userCredential.user.uid, //各マイページにページ遷移する為にuidをfirestoreに格納 }); }) ページを遷移させる為に一度this.uidに 「userCredential.user.uid;」を格納してから ${this.uid}として対象ページに遷移させています。 signup.vue this.uid = userCredential.user.uid; //this.uidに 「userCredential.user.uid;」を格納 ~ 省略 ~ .then(() => { this.$router.push(`/mypage/${this.uid}`); //新規登録後、「/mypage/userCredential.user.uid」で該当ページに遷移 }) uidはどこから取得している? ちなみにthis.uid を取得している箇所は下記になります。 this.uid = userCredential.user.uid; つまり、メールアドレスとパスワードでログインした人の、uid です。 引数に渡されたuserCredentialとは? userCredential という名前自体は、利用者が勝手につけたものです。 別の名前、例えば abc にしても正しく動きますが、意味の分かるものにしているだけです。 変更前 firebase .auth() .createUserWithEmailAndPassword(this.email, this.password) .then((userCredential) => { this.$swal("登録に成功しました。", { icon: "success", }); this.uid = userCredential.user.uid; 変更後 firebase .auth() .createUserWithEmailAndPassword(this.email, this.password) .then((abc) => { this.$swal("登録に成功しました。", { icon: "success", }); this.uid = abc.user.uid; 渡される情報自体( userCredential の値や型)は、firebase が規定したものになります。 (つまり userCredential.user にユーザー情報が入っている、などは決められている) 公式サイト:Auth | JavaScript SDK | Firebase 上記ページを見ると、createUserWithEmailAndPassword は Promise を返すことがわかります。 直後の then の後の userCredential の型が UserCredential です。UserCredential の仕様は以下のページを見るとわかります。 公式サイト:auth | JavaScript SDK | Firebase UserCredential の構造を以下のようになっていることがわかります。 { additionalUserInfo?: AdditionalUserInfo | null; credential: AuthCredential | null; operationType?: string | null; user: User | null }
  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

動的ルートマッチング「this.$route.params」について

動的ルートマッチング「this.$route.params」について 公式サイト:Vue Router 動的ルートマッチング 「this.$route.params」は現在のURLのパラメータを取得する際に使用します。 現在のページが、/signup の場合 現在のURLのパラメータに取得する値がない為、router.params.uidの値は「undefind」なります。 現在のページが、/mypage/hoge の場合 現在のURLのパラメータを取得する為、router.params.uidの値は「hoge」になります。
  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

【Vue × Firebase】動的ルートマッチング「this.$route.params」について

動的ルートマッチング「this.$route.params」について 公式サイト:Vue Router 動的ルートマッチング 「this.$route.params」は現在のURLのパラメータを取得する際に使用します。 現在のページが、/signup の場合 現在のURLのパラメータに取得する値がない為、router.params.uidの値は「undefind」なります。 現在のページが、/mypage/hoge の場合 現在のURLのパラメータを取得する為、router.params.uidの値は「hoge」になります。
  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

Azure Static Web AppsでVuePressサイトをつくーる

はじめに このチュートリアルやっていきます https://docs.microsoft.com/ja-jp/azure/static-web-apps/publish-vuepress 開発環境 Node.js GitHub Azure Windows 10 導入 1.vuepress-static-appフォルダの作成 2.README.mdの作成 README.md # Hello From VuePress 3.node.jsのコマンドプロンプトを起動 cd vuepress-static-app npm init -y npm install --save-dev vuepress 4.package.jsonを編集 package.json { "name": "vuepress-static-app", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "build": "vuepress build", "test": "echo \"Error: no test specified\" && exit 1" }, "keywords": [], "author": "", "license": "ISC", "devDependencies": { "vuepress": "^1.8.2" } } 5..gitignoreを作成 node_modules 6.コミット git init git add . git commit -m "initial commit" 7.https://github.com/new から新しいgitレポジトリを作成(名前はvuepress-static-app, Private、ここでREADMEは作成しない) 8.push git remote add origin https://github.com/SatoshiRobatoFujimoto/vuepress-static-app.git git branch -M main git push -u origin main 9.AzureポータルでStatic Web Appを作成 10.確認および作成 11.GitHub アクションが無事に成功したらURLにアクセス きたこれ 12.ローカルで開発するためにpackage.jsonを編集 { "name": "vuepress-static-app", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "dev": "vuepress dev", "build": "vuepress build", "test": "echo \"Error: no test specified\" && exit 1" }, "keywords": [], "author": "", "license": "ISC", "devDependencies": { "vuepress": "^1.8.2" } } 13.dev環境を起動し、http://localhost:8080/ にアクセスしてみる npm run dev 14.タイトルとナビゲーションを作成する。.vuepressフォルダを作成し、下記のconfig.jsを作成する。 https://github.com/reverentgeek/vuepress-authentication-tutorial config.js module.exports = { title: "My Documentation Site", description: "This is going to be awesome!", themeConfig: { nav: [ { text: "Home", link: "/" }, { text: "About", link: "/about/" } ] } };
  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

Vue.js Axiosについて学ぶ

はじめに RailsやVue.jsなどを学んできましたが データベースとのやりとりの中でaxiosを学ぶ必要があるとわかり 学んだことをまとめておきます。 今回はVue2での実装です。 axiosとは axiosとはブラウザやnode.js上で動くPromiseベースのHTTPクライアントライブラリでGETなどのHTTPリクエストを使ってサーバーからデータの取得、サーバーのデータの更新をすることができます。 JQueryでいうAjaxで、非同期にHTTP通信を容易に実装できるとのこと。 Vue.jsでは非同期通信を行うのにaxiosを使うのがスタンダード。 読み方は「アクシオス」。 インストール npm npm install axios yarn yarn add axios cdn <script src="https://unpkg.com/axios/dist/axios.min.js"><script> 今回はcdnで導入します。 GETメソッドによるデータ取得 GETメソッドはHTTP通信の外部から情報を取得する基本のメソッドです。 GET通信をaxiosでするにはaxios.getメソッドを使用します。 - 第一引数にパラメータ付きのURLを指定して、 - .then()で通信が成功した際の処理を書きます。 - .catchでエラー時の処理を書きます。 - .finally()は通信が成功しても失敗しても常に実行されます。 javascript axios.get('/user?ID=12345') .then(function (response) { // handle success(axiosの処理が成功したとき) console.log(response); }) .catch(function (error) { // handle error(axiosの処理に失敗したとき) console.log(error); }) .finally(function () { // always executed(axiosの結果関係なくいつも実行させたいこと) }); getの引数にURLを入れるだけでURLに対してGETリクエストを送ることができます。 リクエスト後は戻る値は全てresponseの中に保存されます。 レスポンスには以下のものが入ります。 // レスポンスデータ response.data // ステータスコード response.status // ステータステキスト response.statusText // レスポンスヘッダ response.headers // コンフィグ response.config JSONPlaceholder 無料で使えるREST APIの動作確認をオンラインで行うためのサイトです。 axiosで動作確認するために事前にデータを準備する必要がなくなります。 JSONPlaceholder 今回はこちらを利用していきます。 まずはgetメソッドでJSONPlaceholderのusersファイルをリクエストして取得できるかやってみます。 javascript new Vue({ el: '#app', data: { }, mounted :function(){ axios.get('https://jsonplaceholder.typicode.com/users') .then(response => console.log(response)) .catch(error => console.log(error)) } }) mountedでブラウザで読み込んだときにaxiosが実行されるようにしています。 情報を取得できています。 次に Vueインスタンスのdatプロパティに取得したデータ(responce.data)を保存するusersを追加します。 javascript new Vue({ el: '#app', data: { users: [] }, mounted :function(){ axios.get('https://jsonplaceholder.typicode.com/users') .then(response => this.users = response.data) .catch(error => console.log(error)) } }) HTMLにv-forディレクティブを使い、データの内容を表示させます。 html <div id="app"> <ul v-for="user in users"> <li >{{ user.name }}</li> <li>{{ user.email }}</li> </ul> </div> See the Pen Vue.js Axios traning2 by morioka (@rm5912) on CodePen. URLパラメータを指定 URLに直接記述 axios.get('https://jsonplaceholder.typicode.com/users?name=Mike Braun') .then(response => this.users = response.data) .catch(error => console.log(error)) パラメータオプションを使う javascript axios.get('https://jsonplaceholder.typicode.com/users', { params: { name: 'Mike Braun' } }) .then(response => this.users = response.data) .catch(error => console.log(error)) POSTメソッドによる新規作成 axios.postメソッドを使うことで新規にデータを登録することができます。 第二引数に送信したいデータを指定することで送信することができます。 javascript axios.post('/https://jsonplaceholder.typicode.com/users', { firstName: 'Tomas', lastName: 'Waterpool' }) .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); }); 先程のコードに新規データを登録できるようにinput要素を追加して入力、作成できるようにします。 v-modelで新しいdataのnameを設定して、作成ボタンを押すとcreateNewUserメソッドがv-onディレクティブのclickイベントが実行されます。 See the Pen Vue.js Axios traning3 by morioka (@rm5912) on CodePen. unshiftメソッドを使い、先頭に挿入しています。 unshift,shift,pop,pushが混乱するので、絵で整理した
  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

Vue.js Axiosについて学ぶ①

はじめに RailsやVue.jsなどを学んできましたが データベースとのやりとりの中でaxiosを学ぶ必要があるとわかり 学んだことをまとめておきます。 今回はVue2での実装です。 axiosとは axiosとはブラウザやnode.js上で動くPromiseベースのHTTPクライアントライブラリでGETなどのHTTPリクエストを使ってサーバーからデータの取得、サーバーのデータの更新をすることができます。 JQueryでいうAjaxで、非同期にHTTP通信を容易に実装できるとのこと。 Vue.jsでは非同期通信を行うのにaxiosを使うのがスタンダード。 読み方は「アクシオス」。 インストール npm npm install axios yarn yarn add axios cdn <script src="https://unpkg.com/axios/dist/axios.min.js"><script> 今回はcdnで導入します。 GETメソッドによるデータ取得 GETメソッドはHTTP通信の外部から情報を取得する基本のメソッドです。 GET通信をaxiosでするにはaxios.getメソッドを使用します。 - 第一引数にパラメータ付きのURLを指定して、 - .then()で通信が成功した際の処理を書きます。 - .catchでエラー時の処理を書きます。 - .finally()は通信が成功しても失敗しても常に実行されます。 javascript axios.get('/user?ID=12345') .then(function (response) { // handle success(axiosの処理が成功したとき) console.log(response); }) .catch(function (error) { // handle error(axiosの処理に失敗したとき) console.log(error); }) .finally(function () { // always executed(axiosの結果関係なくいつも実行させたいこと) }); getの引数にURLを入れるだけでURLに対してGETリクエストを送ることができます。 リクエスト後は戻る値は全てresponseの中に保存されます。 レスポンスには以下のものが入ります。 // レスポンスデータ response.data // ステータスコード response.status // ステータステキスト response.statusText // レスポンスヘッダ response.headers // コンフィグ response.config JSONPlaceholder 無料で使えるREST APIの動作確認をオンラインで行うためのサイトです。 axiosで動作確認するために事前にデータを準備する必要がなくなります。 JSONPlaceholder 今回はこちらを利用していきます。 まずはgetメソッドでJSONPlaceholderのusersファイルをリクエストして取得できるかやってみます。 javascript new Vue({ el: '#app', data: { }, mounted :function(){ axios.get('https://jsonplaceholder.typicode.com/users') .then(response => console.log(response)) .catch(error => console.log(error)) } }) mountedでブラウザで読み込んだときにaxiosが実行されるようにしています。 情報を取得できています。 次に Vueインスタンスのdatプロパティに取得したデータ(responce.data)を保存するusersを追加します。 javascript new Vue({ el: '#app', data: { users: [] }, mounted :function(){ axios.get('https://jsonplaceholder.typicode.com/users') .then(response => this.users = response.data) .catch(error => console.log(error)) } }) HTMLにv-forディレクティブを使い、データの内容を表示させます。 html <div id="app"> <ul v-for="user in users"> <li >{{ user.name }}</li> <li>{{ user.email }}</li> </ul> </div> See the Pen Vue.js Axios traning2 by morioka (@rm5912) on CodePen. URLパラメータを指定 URLに直接記述 axios.get('https://jsonplaceholder.typicode.com/users?name=Mike Braun') .then(response => this.users = response.data) .catch(error => console.log(error)) パラメータオプションを使う javascript axios.get('https://jsonplaceholder.typicode.com/users', { params: { name: 'Mike Braun' } }) .then(response => this.users = response.data) .catch(error => console.log(error)) POSTメソッドによる新規作成 axios.postメソッドを使うことで新規にデータを登録することができます。 第二引数に送信したいデータを指定することで送信することができます。 javascript axios.post('/https://jsonplaceholder.typicode.com/users', { firstName: 'Tomas', lastName: 'Waterpool' }) .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); }); 先程のコードに新規データを登録できるようにinput要素を追加して入力、作成できるようにします。 v-modelで新しいdataのnameを設定して、作成ボタンを押すとcreateNewUserメソッドがv-onディレクティブのclickイベントが実行されます。 See the Pen Vue.js Axios traning3 by morioka (@rm5912) on CodePen. unshiftメソッドを使い、先頭に挿入しています。 unshift,shift,pop,pushが混乱するので、絵で整理した 参考サイト vue.jsを使ってaxiosを学ぶ axiosライブラリを使って、柔軟にHTTP通信を行う 【Ajax】axiosを使って簡単にHTTP通信 axiosの使い方まとめ (GET/POST/例外処理)
  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

VueCLIコンポーネント全体にcssを適用する

全体にReboot.cssを適用する Reboot.cssとは Bootstrap 4に含まれているCSSリセットのこと。 Reboot.cssはnormalize.css 2.0に似ており、リセットの素晴らしい機能がある。 ・box-size: border-box;はデフォルトで、すべての要素に適用されます。 ・クロスブラウザに対応した一貫したリセットを提供しています。 ・要素にシンプルで自然なベーススタイルを与えます。 ・モダンなCSSを記述するためのヒントが記されています。 src/App.vue <template> <div id="app"> <!--省略--> </div> </template> <script> //省略 </script> <style> /* ファイルパスに従って@importntの後にファイルパスを書き込む */ @import "./assets/styles/bootstrap-reboot.css"; /* 省略 */ </style> ルートコンポーネントであるApp.vueのStyleタグに読み込みたい外部CSSファイルを指定する。 参考
  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

CodeMirrorをTypescript+Vue.jsで使う方法

概要 CodemirrorはJavaScript製の多言語に対応したテキストエディタです。 今回は、このCodeMirrorをTypescript+Vue.jsな環境で使えるように実装してみました。 準備 vue create vue-codemirror-sample cd vue-codemirror-sample vueのバージョンは2.x 必要な機能は TypeScript、後はお好みで スタイルはVue.extend()で書きます。 class style派は置き換えて読んでください。 ライブラリのインストール npm install codemirror npm install @types/codemirror 実装 CodeMirrorを読み込む まずは、App.vueからいらないコードを消してスッキリさせます。 App.vue <template> <div id="app"> - <img alt="Vue logo" src="./assets/logo.png" /> - <HelloWorld msg="Welcome to Your Vue.js + TypeScript App" /> </div> </template> <script lang="ts"> import Vue from 'vue' -import HelloWorld from './components/HelloWorld.vue' export default Vue.extend({ name: 'App', - components: { - HelloWorld, - }, }) </script> -<style> -#app { - font-family: Avenir, Helvetica, Arial, sans-serif; - -webkit-font-smoothing: antialiased; - -moz-osx-font-smoothing: grayscale; - text-align: center; - color: #2c3e50; - margin-top: 60px; -} -</style> 次にcodemirrorを挿入します。 見ずらいので追加でmonokaiテーマも追加します。 App.vue <template> <div id="app"> + <textarea id="editor"></textarea> </div> </template> <script lang="ts"> +import CodeMirror, { EditorConfiguration, Editor } from 'codemirror' +import 'codemirror/lib/codemirror.css' +import 'codemirror/theme/monokai.css' import Vue from 'vue' +type DataType = { + editor?: Editor +} export default Vue.extend({ name: 'App', + data(): DataType { + return {} + }, + // mountedでCodemirrorを生成する + mounted(): void { + const editor: HTMLTextAreaElement | null = document.querySelector('#editor') + if (editor == null) { + throw new Error('codemirrorを挿入するtextariaがありません') + } + const config: EditorConfiguration = { + theme: 'monokai', + lineNumbers: true, + } + this.editor = CodeMirror.fromTextArea(editor, config) + }, }) </script> これでとりあえず読み込めるようになりました。 アドオンの追加方法 アドオンの追加は、importするだけです。 import 'codemirror/addon/hint/show-hint.js' jsで自動補完とシンタックスハイライトを使えるようにしてみます。 App.vue <template> <div id="app"> <textarea id="editor"></textarea> </div> </template> <script lang="ts"> import CodeMirror, { EditorConfiguration, Editor } from 'codemirror' import 'codemirror/lib/codemirror.css' import 'codemirror/theme/monokai.css' +import 'codemirror/addon/hint/show-hint.js' +import 'codemirror/addon/hint/show-hint.css' +import 'codemirror/mode/javascript/javascript.js' +import 'codemirror/addon/hint/javascript-hint.js' import Vue from 'vue' type DataType = { editor?: Editor } export default Vue.extend({ name: 'App', data(): DataType { return {} }, mounted(): void { // mountedでCodemirrorを生成する const editor: HTMLTextAreaElement | null = document.querySelector('#editor') if (editor == null) { throw new Error('codemirrorを挿入するtextariaがありません') } const config: EditorConfiguration = { theme: 'monokai', + mode: 'javascript', lineNumbers: true, + showHint: true, + extraKeys: { 'Ctrl-Space': 'autocomplete' }, } this.editor = CodeMirror.fromTextArea(editor, config) }, }) </script> これで、ctrl+spaceキーでjsの自動補完とシンタックスハイライトが使えるようになりました。 おわり 完成したApp.vue App.vue <template> <div id="app"> <textarea id="editor"></textarea> </div> </template> <script lang="ts"> import CodeMirror, { EditorConfiguration, Editor } from 'codemirror' import 'codemirror/lib/codemirror.css' import 'codemirror/theme/monokai.css' import 'codemirror/mode/javascript/javascript.js' import 'codemirror/addon/hint/show-hint.js' import 'codemirror/addon/hint/show-hint.css' import 'codemirror/mode/javascript/javascript.js' import 'codemirror/addon/hint/javascript-hint.js' import Vue from 'vue' type DataType = { editor?: Editor } export default Vue.extend({ name: 'App', data(): DataType { return {} }, mounted(): void { // mountedでCodemirrorを生成する const editor: HTMLTextAreaElement | null = document.querySelector('#editor') if (editor == null) { throw new Error('codemirrorを挿入するtextariaがありません') } const config: EditorConfiguration = { theme: 'monokai', mode: 'javascript', lineNumbers: true, showHint: true, extraKeys: { 'Ctrl-Space': 'autocomplete' }, } this.editor = CodeMirror.fromTextArea(editor, config) }, }) </script>
  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

【Vue 3】コンポーネント間のデータの受渡し【基礎】

1. はじめに   1-1. はじめに Vueのコンポーネント間のデータの受渡しが「親→子」「子→親」で異なり複雑です。 私の頭を整理するために、この記事を記載しています。 1-2. 説明の前に・・・ 説明で使用するプログラム ( x.html, x.js ) は、下記の.htmlファイルに記載する前提での説明です。 また、記載はVue3ですが、基本的にVue2でも同じ考え方です。 index.html <!DOCTYPE html> <html lang="ja"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <script src="https://unpkg.com/vue@next"></script> <title>vue sample</title> </head> <body> <div id="app"> // ************************************** // ここにx.htmlを記載 // ************************************** </div> <script> // ************************************** // ここにx.jsを記載 // ************************************** </script> </body> </html> 2. コンポーネントの基礎 2-1. コンポーネントとは コンポーネントは「名前付きの再利用可能なインスタンス」です。 2-1.jsのようにコンポーネントを定義し、2-1.htmlで定義したコンポーネントを3つ使用しています。 コンポーネントが再利用され、3つのボタンが表示されます。 2-1.html <div id="app"> <Counter></Counter> <Counter></Counter> <Counter></Counter> </div> 2-1.js // アプリケーションの生成 const app = Vue.createApp({}) // コンポーネントを定義 (第一引数:コンポーネントの名前, 第二引数:コンポーネントオブジェクト) app.component('Counter',{ data() { return { count : 0 } }, template: ` <button v-on:click="count++"> コンポーネントだよ:{{count}} </button> ` }) // id="app" にマウント app.mount('#app') 2.2 グローバルコンポーネントとローカルコンポーネント コンポーネントには2種類あります。グローバルコンポーネントとローカルコンポーネントです。 グローバルコンポーネント アプリケーションのcomponentメソッドを利用します。 アプリケーション内のどのコンポーネントのテンプレートでも使用できます。 2-1で定義したコンポーネントもグローバルコンポーネントです。 実際はビルドの最適化を高めるために、ローカルコンポーネントで定義するほうが一般的です。    ローカルコンポーネント オブジェクトを定義して、componentsオプションで登録します。  componentsで登録したコンポーネント内でのみ使用できます。 以下の例は、ローカルコンポーネントChildをグローバルコンポーネントParentのcomponentsに登録しています。 Parentの中でのみChildが使用できるようになります。 この際、Parentを親コンポーネント(以降、親)、Childを子コンポーネント(以降、子)といいます。1 2-2.html <div id="app"> <Parent></Parent> </div> 2-2.js // アプリケーションの生成 const app = Vue.createApp({}) // ローカルコンポーネント+子コンポーネント // オブジェクトを定義 const Child = { template: ` <h2> Child ! </h2> ` } // グローバルコンポーネント+親コンポーネント app.component('Parent',{ // コンポーネントの登録をする components: { Child }, // 親コンポーネントの中で子コンポーネントは使用できる template: ` <h1> Parent ! </h1> <Child></Child> ` }) // id="app" にマウント app.mount('#app') 3. コンポーネント間のデータの受渡しの基礎 3-1. 親コンポーネントから子コンポーネントへのデータの受渡し 子にpropsオプションを定義します。親からデータを渡すときはhtmlの属性を使用するように渡すことができます。 基本的にVueでは親から子への単方向のデータフローです。 propsの定義の仕方を変えると、バリデーションも付けられます。 3-1.html <div id="app"> <Parent></Parent> </div> 3-1.js // アプリケーションの生成 const app = Vue.createApp({}) // 子コンポーネント const Child = { // 親から受け取るdataを定義 props:['parentData'], template: ` <h2> Child ! </h2> <h2> {{parentData}} </h2> ` } // 親コンポーネント app.component('Parent',{ components: { Child }, // htmlの属性のように記載してデータを渡す template: ` <h1> Parent ! </h1> <Child parentData="親コンポーネントから書き換え!"></Child> ` }) 3-2. 子コンポーネントから親コンポーネントへのデータの受渡し Vueは親から子への単方向データフローです。そのため、子から親へデータを受け渡すには少し工夫が必要です。 $emitを使用して、子から親のイベントを発火させます。 イベントで設定されたJavaScriptやメソッドを実行させ、その中で親のデータを変更します。 データの受取り方法は2種類あります。$eventを使用する方法とメソッドの第一引数で受け取る方法です。 3-2.html <div id="app"> <Parent></Parent> </div> 3-2.js const app = Vue.createApp({}) // 子コンポーネント const Child = { // $emitの第一引数はイベント名(childData)、第二引数は渡す値("親に渡すデータ")を定義 template: ` <button v-on:click='$emit("childData","親へ渡すデータ")'>親へデータ渡すボタン</button> ` } // 親コンポーネント app.component('Parent',{ data() { return { eventData: '', // $eventで渡したデータを格納 methodData: '', // メソッドで渡したデータを格納 } }, components: { Child }, // $eventを使用する方法とメソッドで渡す方法がある template: ` <h1> Parent ! </h1> <h3>1. $eventを使用する方法</h3> <Child v-on:childData="eventData = $event"></Child> eventData : {{eventData}} <h3>2. メソッドで渡す方法</h3> <Child v-on:childData="changeParentData"></Child> methodData : {{methodData}} `, methods: { // methodの第一引数としてデータが渡される changeParentData(event) { this.methodData = event } } }) // id="app" にマウント app.mount('#app') 4. おわりに 最後まで読んでいただきありがとうございました。今回の記事のポイントは以下です。 Vueは親コンポーネントから子コンポーネントへの単一方向のデータフローである。 親→子:子でpropsを用いてデータを受け取る。 子→親:子にて$emitを使用してイベントを起動。親にて$eventやメソッドでデータを受け取る。 記載の誤りや、文字の揺らぎがあるかもしれません。ご指摘がありましたらコメントいただけると幸いです。 詳細が知りたい方や、より正確な情報を知りたい方は参考URL(Vue3公式ページ)を参照してください。 参考URL 親はグローバルコンポーネント、子はローカルコンポーネントというルールはありません。componentsオプションを定義しているのが親、定義に使用されているのが子です。  ↩
  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む