質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.48%
Vue.js

Vue.jsは、Webアプリケーションのインターフェースを構築するためのオープンソースJavaScriptフレームワークです。

Ruby on Rails

Ruby on Railsは、オープンソースのWebアプリケーションフレームワークです。「同じことを繰り返さない」というRailsの基本理念のもと、他のフレームワークより少ないコードで簡単に開発できるよう設計されています。

Q&A

解決済

1回答

1615閲覧

vue.js リロード後の初期化を防ぎたいです

Taka2401

総合スコア8

Vue.js

Vue.jsは、Webアプリケーションのインターフェースを構築するためのオープンソースJavaScriptフレームワークです。

Ruby on Rails

Ruby on Railsは、オープンソースのWebアプリケーションフレームワークです。「同じことを繰り返さない」というRailsの基本理念のもと、他のフレームワークより少ないコードで簡単に開発できるよう設計されています。

0グッド

0クリップ

投稿2021/09/13 06:58

編集2021/09/13 12:16

実現したいこと

vueでフォロー機能を実装しています。
リロードしてもデータが初期化されないようにしたいです。

発生している問題

フォローボタンをクリックすると問題なく動作しますが、
一度リロードするとフォロー、フォロワーのカウントが0になり初期化されてしまいます。

該当のソースコード

RelationshipButton.vue

<template> <div> <p>{{ followingCount }} フォロー</p> <p>{{ followersCount }} フォロワー</p> <div v-if="isRelationshiped" @click="deleteRelationship()" class="btn btn-bg follow-followed"> <i class="fas fa-user-minus"></i> フォロー解除 </div> <div v-else @click="registerRelationship()" class="btn btn-bg" style="margin:0;"> <i class="fas fa-user-plus"></i> フォローする </div> <pre>{{ $data }}</pre> </div> </template> <script> import axios from 'axios' import { csrfToken } from 'rails-ujs' axios.defaults.headers.common['X-CSRF-TOKEN'] = csrfToken() export default { props: ['followerId', 'followedId'], data() { return { relationshipList: [], followingCount: 0, followersCount: 0, // localstrageの設定 //countData: '' } }, // localstrageの設定 // mounted() { // if (localStorage.countData) { // this.countData = localStorage.countData; // } // }, // watch: { // countData(newcountData) { // localStorage.countData = newcountData; // } // }, computed: { count() { return this.relationshipList.length }, isRelationshiped() { if (this.relationshipList.length === 0) { return false } return Boolean(this.findRelationshipId()) } }, created: function() { this.fetchRelationshipByFollowedId().then(result => { this.relationshipList = result }) }, methods: { fetchRelationshipByFollowedId: async function() { const res = await axios.get(`/api/v1/relationships/?followed_id=${this.followedId}`) if (res.status !== 200) { process.exit() } return res.data }, registerRelationship: async function() { const res = await axios.post('/api/v1/relationships', { followed_id: this.followedId }) this.followersCount += 1; if (res.status !== 201) { process.exit() } this.fetchRelationshipByFollowedId().then(result => { this.relationshipList = result }) }, deleteRelationship: async function() { const relationshipId = this.findRelationshipId() const res = await axios.delete(`/api/v1/relationships/${relationshipId}`) this.followersCount -= 1; if (res.status !== 200) { process.exit() } this.relationshipList = this.relationshipList.filter(n => n.id !== relationshipId) }, findRelationshipId: function() { const relationship = this.relationshipList.find((relationship) => { return (relationship.follower_id === this.followerId) }) if (relationship) { return relationship.id } } } } </script>

follows.html.erb

<%= javascript_pack_tag 'relationship' %> <% if current_user.id === user.id %> <%= link_to "#{user.followings.count} フォロー", following_user_path(user), class: "link-color" %> <span> | </span> <%= link_to "#{user.followers.count} フォロワー ", followers_user_path(user), class: "link-color" %> <% end %> <div id="relationship"> <% if current_user.id != user.id %> <keep-alive> <Relationship-button :follower-id="<%= current_user.id %>" :followed-id="<%= @user.id %>"></Relationship-button> </keep-alive> <% end %> </div>

relationships_controller.rb

module Api module V1 class RelationshipsController < ActionController::API before_action :authenticate_user! def index render json: Relationship.filter_by_followed(params[:followed_id]).select(:id, :follower_id, :followed_id) end def create current_user.relationships.create(relationships_params) head :created end def destroy current_user.relationships.find(params[:id]).destroy! head :ok end private def relationships_params params.require(:relationship).permit(:followed_id) end end end end

試したこと

follows.html.erbのコンポーネントにkeep-aliveを使ってデータをキャッシュできるように設定。

https://jp.vuejs.org/v2/cookbook/client-side-storage.html を参考に
localstrageでデータを保持できよう設定を行ってみましたが、検証ツールでデータが確認できませんでした。

調べたところ、localstrageやvuexを使いstoreでデータを保持するとのことですが、
大規模ではない場合localstrageを使ったほうが適切でしょうか。

補足情報(FW/ツールのバージョンなど)

windows10 home
Ruby 2.6.3
Ruby on Rails 5.2.6

解決に繋がるヒントを頂けますと幸いです。
よろしくお願いいたします。

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

guest

回答1

0

自己解決

localstorage.getItem() localstorage.setItemを使いlocalstorageに登録することで解決できました。

投稿2021/09/14 13:13

編集2021/09/14 13:14
Taka2401

総合スコア8

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.48%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問