1

столкнулась с проблемой. Не получатся динамически обновлять количество подписчиков (без перезагрузки страницы). Я только учусь, если есть другой вариант проще, можете подсказать пожалуйста

Так же есть кнопка, надпись которой меняется в зависимости от статуса (подписан/отписан)

    <div class="row justify-content-center">
      <div class="col-3 text-center numb">{{$followCount}}</div>
      <div class="col-3 text-center numb">{{$followingCount}}</div>
    </div>

    <example-component follow-count="{{$followCount}}" user-id='{{ $user->id }}' follow='{{ $follow }}'></example-component>

количество подписчиков и подписок подсчитывается в контроллере

class ProfileController extends Controller
{
  public function index(User $user)
  {
      $followCount=$user->profile->followers->count();
      $followingCount=$user->following->count();
      return view('profiles.index', compact('user', 'follow', 'postCount', 'followCount', 'followingCount'));
  }
}

vue

<template>
    <div class="container">
          <div class="col-12 text-center"><button class="btn btn-primary" @click="follows" v-text="buttonText"></button></div>
    </div>
</template>

<script>
    export default {
        props: ['userId', 'follow'],
        data: function () {
            return {
                status: this.follow,


            }
        },
        methods: {
            follows() {
                axios.post('/follow/' + this.userId)
                    .then(response => {
                        this.status =! this.status;
                    });
            }
        },
        computed: {
            buttonText() {
                return (this.status) ? 'Folgen' : 'Abonniert';
            },
        }
    }
</script>

так, у меня получаются следующие файлы в resources/js/components ExampleComponent.vue

<template>
    <div class="container">
          <div class="col-12 text-center"><button class="btn btn-primary" @click="follows" v-text="buttonText"></button></div>
    </div>
</template>

<script>
    import FollowBus from 'FollowBus'
    export default {
        props: ['userId', 'follow', 'followCount'],
        data: function () {
            return {
                status: this.follow,

            }
        },
        mounded: function() {
         // отслеживаем status
         this.$watch('status', (newStatus, oldStatus) => {
            FollowBus.$emit('follow_change', newStatus)
         })
        },
        methods: {
            follows() {
                axios.post('/follow/' + this.userId)
                    .then(response => {
                        this.status =! this.status;
                        console.log(this.followCount);
                    });


            }
        },
        computed: {
            buttonText() {
                return (this.status) ? 'Abonniert' : 'Folgen';
            },
        }
    }
</script>

FollowCounter.vue

<template>
 <div class="col-3 text-center numb">{{followCount}}</div>
</template>
<script>
   import FollowBus from 'FollowBus'

   export default {
      data: function () {
         return {
            count: 0
         }
      },
      mounted: function () {
        // подписываемся на событие
        FollowBus.$on('follow_change', (status) => {
           // подгрузка при возникновении события
           this.loadCounters()
        })

        // подгрузка при монтировании
        this.loadCounters()
      },
      methods: {
         loadCounters: function () {
            axios.get(url).then((response) => {
              // извлекаем данные из response.data
              // this.count =
            })
         }
      }
  }
</script>

FollowBus.js

import Vue from 'vue'

export default FollowBus = new Vue();

при этом видарт ошибку Module not found: Error: Can't resolve 'FollowBus'

1
  • Если ответ ниже помог вам — отметте его, как решение.
    – doox911
    15 июл 2019 в 19:04

1 ответ 1

0

создать компонент - шину событий (файл FollowBus.js)

import Vie from 'vue'

export default FollowBus = new Vie();

при изменении статуса в вашем компоненте (example-component) послать событие в шину

...
<script>
   import FollowBus from 'FollowBus'

   export default {
      ...
      mounded: function() {
         // отслеживаем status 
         this.$watch('status', (newStatus, oldStatus) => {
            FollowBus.$emit('follow_change', newStatus)
         })
      }
      ...
   }
</script>

в компоненте вывода количества подписчиков (назовем FollewerCounter.vue) подписаться на событие, подгружать подписчиков по событию 'follow_change'

код FollewerCounter.vue

    <template>
        <div class="row justify-content-center">
          <div class="col-3 text-center numb">{{followCount}}</div>
          <div class="col-3 text-center numb">{{followingCount}}</div>
        </div>
    </template>
    <script>
       import FollowBus from 'FollowBus'

       export default {
          data: function () {
             return {
                followCount: 0,
                followingCount: 0,
             }
          },
          mounted: function () {
            // подписываемся на событие
            FollowBus.$on('follow_change', (status) => {
               // подгрузка при возникновении события
               this.loadCounters()
            })

            // подгрузка при монтировании
            this.loadCounters()
          },
          methods: {
             loadCounters: function () {
                axios.get(url).then((response) => {
                  // извлекаем данные из response.data
                  // this.count = 
                })
             }
          }
      }
    </script>

подключаем компонент в файле инициализации приложения app.js (или main.js) аналогично example-component

Vue.component('folower-couner', '<путь>/FollewerCounter.vue')

добавляем в html

<folower-couner></folower-couner>
<exanle-component ...></exanle-component>

в контроллере laravel

class ProfileController extends Controller
{
    public function index(User $user)
    { 
       ... 
       получение данных
       ... 

       if ($request->ajax()) {
          // для ajax запросов
          $data = compact('followCount', 'followingCount'));

          return response()
            ->json($data, 200)
            ->setEncodingOptions(JSON_NUMERIC_CHECK);
       }

       $data = compact('user', 'follow', 'postCount'));        
       return return view('profiles.index', $data);
    }
 }
5
  • большое спасибо! не подскажите, как интегрировать код в готовый компонент, т.е. в ExampleComponent.vue? 8 июл 2019 в 13:18
  • я не совсем до конца понимаю принцип, но не получается интегрировать. Где в HTML нужно вставить follow-component? Выше приложила измененный код 9 июл 2019 в 7:59
  • follow-component вместо верстки вывода счетчиков, верстку перенести в шаблон компонента FollewerCounter.vue 9 июл 2019 в 13:03
  • постоянно видеть ошибку Module not found: Error: Can't resolve 'FollowBus' 9 июл 2019 в 15:07
  • попробуйте в начале пути указать ./ (текущая директория): import FollowBus from './FollowBus.js' 10 июл 2019 в 11:32

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.