如何从 laravel 控制器访问数据 ($count) 到 vue 组件

how to access data ($count) from laravel controller to vue component

我想从我的控制器访问变量 $count 并将其访问到 vue 组件(前端)。目前我的控制器上有这段代码:

public function index()
{
    $count = User::where('created_at', Carbon::today())->count();
    return view('user.index', compact('count'));
}

我对 laravel 和 vuejs 很陌生,所以请帮助我。谢谢!

将计数作为 prop 从 blade 发送到组件

<your-component-name :count="{{ $count }}"></your-component-name>

然后从您的组件中接收该道具

<template>
    <div>
        Count is {{ count }}
    </div>
</template>

<script>
export default {
    props: {
        count: {
            type: Number
        }
    }
}
</script>

To pass down data to your components you can use props. Find more info about props over here. This is also a good source for defining those props.

You can do something like:

<example :userId="{{ Auth::user()->id }}"></example>

OR

<example v-bind:userId="{{ Auth::user()->id }}"></example>

And then in your Example.vue file you have to define your prop. Then you can access it by this.userId.

Like :

<script>
  export default {
    props: ['userId'],
    mounted () {
      // Do something useful with the data in the template
      console.dir(this.userId)
    }
  }
</script>

上面的问题在下面的问题中得到了回答