20220108のvue.jsに関する記事は3件です。

Vue 目次 (自分用)

メソッド一覧 ・mount ・create ・stop ・prevent データバインディング ・v-bind ・v-html ・v-for ・v-on →:input,keyup,  [メモ]Vue.jsイベント修飾子一覧 ・v-model ・v-if ・タグ 使用用途 ・リンクを展開の中で使う。 ・繰り返しの出力 専門用語 ・ライフサイクル ・{{ }} - 展開(Interpolation) ・バインディング ・ディレクティブ ・コンポーネントについて  学ぶべきは主に基本機能は主に3つ  ・Props  ・Custom Events  ・Provide-Inject  応用  ・component Registraction & Styling  グローバルコンポーネントとローカルコンポーネントの違い!  CSSのテンプレートの一部のみに戻る方法  スロットの説明  スコープスロットに説明  データを送るらしい。  動的コンポーネント  テレポート  v-slot  ・Slots & Dynamic Components  ・Naming & Folder Structure 動的コンポーネント ・キープアライブコンポーネント
  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

【Vue.js】Twitterシェア ツイートの中身の指定(2週間後の日付、本のタイトル)

はじめに こんにちは! 今回は【Vue.js】Twitterシェアボタンの実装についてアウトプットしていきます! 前回の記事でTwitterシェアの実装を行いました!今回はツイートのコメント部分に、 ①2週間後の日付 ②診断結果ででた本のタイトル を自動的に記入される機能を実装していきます! 対象 ・vue.jsでTwitterシェアを実装したい方 ・vue.jsで日付を取得し表示させたい方 ・前回の記事までの内容を実装済みの方。 使用環境 使用技術 バージョン nuxt.js 2.15.7 @nuxtjs/tailwindcss 4.2.0 moment 2.29.1 nuxt-microcms-module 2.0.0 使用ファイル,概要 ファイル名 概要 pages/result.vue 診断結果表示ページ 実装 pages/result.vue <template> <div class="twitter_share"> <button @click="twitterShare" class=" border-2 border-blue-600 rounded-full h-14 w-64 items-center flex justify-center m-auto my-8 hover:bg-blue-200 duration-1000 " > Twitterで宣言する! </button> </div> </template> <script> import moment from "moment"; export default { async asyncData({ query, $microcms }) { const id = query.id; console.log(id); const book = await $microcms.get({ endpoint: "books", contentId: id, }); console.log(book); return { book, }; }, data() { return { book: "", }; }, methods: { twitterShare() { const today = new Date(); //今日この瞬間の情報を取得 const date_today = today.getDate(); //日 const after2Week = today.setDate(date_today + 14); //今日の日+14日 const formatDate = moment(after2Week).format("MM月DD日"); //2週間後の日にちを"MM月DD日"で表示 console.log(formatDate); //シェアする画面を設定 var shareURL = "https://twitter.com/intent/tweet?text=" + `${formatDate}までに「${this.book.title}」を読み、感想をツイートします!` + "%20%23NewSelf" + "%20%23書籍診断アプリ" + "&url=" + "https://www.google.com/?hl=ja"; //アプリURL //シェアようの画面へ移行 location.href = shareURL; }, }, }; </script> ・microCMSのAPI取得の処理の部分の解説は省かせていただきます。 ①2週間後の日付の実装 pages/result.vue <script> import moment from "moment"; export default { data() { return { moment: ``, }; }, filters: { moment: function (date) { return moment(date).format("MM月DD日"); }, }, methods: { twitterShare() { const today = new Date(); //今日この瞬間の情報を取得 const date_today = today.getDate(); //日 const after2Week = today.setDate(date_today + 14); //今日の日+14日 const formatDate = moment(after2Week).format("MM月DD日"); //2週間後の日にちを"MM月DD日"で表示 console.log(formatDate); //シェアする画面を設定 var shareURL = "https://twitter.com/intent/tweet?text=" + `${formatDate}までに「${this.book.title}」を読み、感想をツイートします!` + "%20%23NewSelf" + "%20%23書籍診断アプリ" + "&url=" + "https://www.google.com/?hl=ja"; //アプリURL //シェアようの画面へ移行 location.href = shareURL; }, }, }; </script> 1.momentのインストール 以下をターミナルに記述しmomentをインストールします。 npm install vue-moment インストールが完了したら、package.jsonに このように記載されていたらOKです! 2.日付を取得?2週間後の日付にカスタマイズ pages/result.vue <script> import moment from "moment"; export default { methods: { twitterShare() { const today = new Date(); //new Date()で今日この瞬間の情報を取得し、定数todayへ代入 const date_today = today.getDate(); //today.getDate()で今日の日にちのみを取得し定数date_todayへ代入 const after2Week = today.setDate(date_today + 14); //today.setDate(date_today + 14)で今日の日+14日に内容変更し、定数after2Weekへ代入 const formatDate = moment(after2Week).format("MM月DD日"); //2週間後の日にちを"MM月DD日"で表示される処理を定数formatDateに代入 console.log(formatDate); //シェアする画面を設定 var shareURL = "https://twitter.com/intent/tweet?text=" + `${formatDate}までに「${this.book.title}」を読み、感想をツイートします!` + //定数formatDateを${}で囲みツイートコメント部分に記載することで実装完了! "%20%23NewSelf" + "%20%23書籍診断アプリ" + "&url=" + "https://www.google.com/?hl=ja"; location.href = shareURL; }, }, </script> 上記の処理でOKです! ②診断結果ででた本のタイトルの表示 pages/result.vue <script> export default { async asyncData({ query, $microcms }) { const id = query.id; console.log(id); const book = await $microcms.get({ endpoint: "books", contentId: id, }); console.log(book); return { book, }; }, data() { return { book: "", }; }, //?での処理を簡単に解説すると、endpointとcontentIdを定数bookに返している。つまりmicroCMSにの登録情報がbookに入っている。なのであとはTwitterシェアのコメント部分に呼び出せばOK! methods: { twitterShare() { var shareURL = "https://twitter.com/intent/tweet?text=" + `${formatDate}までに「${this.book.title}」を読み、感想をツイートします!` + //?${this.book.title}で呼び出せば実装完了! "%20%23NewSelf" + "%20%23書籍診断アプリ" + "&url=" + "https://www.google.com/?hl=ja"; location.href = shareURL; }, }, </script> ・microCMSの処理に関してはこちらの記事に簡単な基礎がまとめてありますので参考にしてみてください。 動作確認 診断を終え、「Twitterで宣言する!」ボタンをクリック 2週間後の日付もタイトル名も無事実装できました!! まとめ 今回はTwitterシェア ツイートの中身の指定(2週間後の日付、本のタイトル)について記事にしました。 よりユーザーが使いやすく、手間のかからないアプリにするにはどうすればいいかを考えていきながら、今後も制作していきたいと思います!よりユーザー目線の思考を磨いていきます! ぜひ参考にしてみていただけるととても嬉しいです!! 今回の記事を読んで質問、間違い等あればコメント等頂けると幸いです。 最後までご愛読ありがとうございました!
  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

Vue3, VTU, Jestで Composition API テストにめちゃくちゃ苦労した話

Vue3 のテストを VTU(Vue Test Utils) と Jest で実施するに当たり環境構築から実際にテストするまでに詰まりまくったのでまとめたいと思います。 環境構築編 Vue3 に対応しているのが VTU2系のためこちらをインストールしてテストランナーである Jest でテスト走らせるというのをやっていきます。 VTU2 : https://next.vue-test-utils.vuejs.org/installation/ Jest : https://jestjs.io/ 結論 最初に結論を申し上げますが、各ライブラリの依存関係がとても難しいので、慣れてる人でない限り公式で用意されているデモを元に環境構築したほうが無難です。 私はこの環境構築に半日以上費やして、結局うまく行きませんでした ? 公式サイトのデモ : https://github.com/lmiller1990/vtu-next-demo ES6でプロジェクト進めている方は Jest がサポートしていないので、別に Babel というコンパイラを入れる必要があります。 Babel : https://babeljs.io/ 私は ES6 で書いていたので、VTU2, Jest, Babel その他にも細かなライブラリを入れる必要があり、慣れている人でないと恐らく難しいです。。。 とりあえずこれで動くよ! 2022年1月8日現在ならこれでとりあえず動きます!自分の備忘録のためにも記載しておきます。 package.json "@vue/test-utils": "^2.0.0-alpha.8", "@babel/preset-env": "^7.9.0", "@types/jest": "^25.2.1", "babel-jest": "^25.2.6", "jest": "^25.2.7", "ts-jest": "^25.3.1", "vue-jest": "^5.0.0-alpha.1", jest.config.js module.exports = { preset: 'ts-jest', globals: {}, testEnvironment: 'jsdom', transform: { "^.+\\.vue$": "vue-jest", "^.+\\js$": "babel-jest" }, moduleFileExtensions: ['vue', 'js', 'json', 'jsx', 'ts', 'tsx', 'node'] } babel.config.js module.exports = { presets: [ [ "@babel/preset-env", { targets: { node: "current", }, }, ], ], }; テスト実施編 さぁ、これでテストが動くようになったわけですが、実際にテストやってみてさらに詰まる。 テスト基本 以下のコンポーネントは公式サイトのもの引用しています。 <template> <div> <div v-for="todo in todos" :key="todo.id" data-test="todo"> {{ todo.text }} </div> </div> </template> <script> export default { name: 'TodoApp', data() { return { todos: [ { id: 1, text: 'Learn Vue.js 3', completed: false } ] } } } </script> 上記のコンポーネントをテストするには以下のようになります。こちらも公式サイトのもの引用です。 import { mount } from '@vue/test-utils' import TodoApp from './TodoApp.vue' test('renders a todo', () => { const wrapper = mount(TodoApp) const todo = wrapper.get('[data-test="todo"]') expect(todo.text()).toBe('Learn Vue.js 3') }) なにやってるかざっくり申し上げますと mount(TodoApp) で TodoApp コンポーネントをマウントしたものを wrapper に入れる。 wrapper.get で DOM を取得( find 的なことしてます)。 todo.text() で取得した DOM のテキストを出力 となります。 Vue の Unit テストではこのように「何が出力されているか」をテストしたりします。 問題点 DOMが取得できない 先程の例でいうと todo.text() をすると Cannot call text on an empty DOMWrapper. ってエラーが出ました。 いや。。。なんでなん? これが本当によくわかりませんでした。 いろいろ調べた結果2つの要素がエラーの原因でした。 原因① 「テストしているコンポーネントが Async コンポーネントだった」 業務中に出たエラーなので詳しくコードは書けませんが、Composition Api の <script lang="ts" setup> 構文を使用しており、 Async コンポーネントになっていました。 Github の issue にあがっていましたが、 Async コンポーネントには <Suspense> でコンポーネントを囲って挙げないといけないようです。 issue : https://github.com/vuejs/vue-test-utils-next/issues/1207#issuecomment-1004825195 test('Suspense', () => { const Component = defineComponent({ components: { Async }, template: '<Suspense><Async/></Suspense>' }) const wrapper = mount(Component) // ... }) この間出た issue みたい。これなかったらマジで詰んでました。。。 原因② 「DOMのマウントが終わっていない状態だった」 DOM の生成が終わる前にアクセスしてしまっているため、async コンポーネントは処理が終わったことを担保しないとアクセスできないようです。 (参考にした issue あったのですがちょっと見つかりませんでした。すみません。) 処理の終了を担保するために flushPromise() というメソッドを使用しました。 https://next.vue-test-utils.vuejs.org/api/#flushpromises 最終的なコード it("display Hello World", async () => { const Component = defineComponent({ components: { TestComponent }, template: "<Suspense><TestComponent/></Suspense>", }); wrapper = mount(Component); expect(wrapper).toBeTruthy(); expect(wrapper.exists()).toBe(true); await flushPromises(); // ここからアクセスできるようになる const h1El = wrapper.find("h1"); expect(h1El.text()).toBe("h1text"); }); 上記で DOM にアクセスできるようになりました!
  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む