我想学习Vue,并希望将其与Laravel集成使用。 我只想从Blade发送用户ID到Vue组件,以便我可以在那里执行PUT请求。 假设我在Blade中有以下代码:
<example></example>
我该如何将 Auth::user()->id 发送到这个组件并使用它呢?我一直在寻找答案,但没有找到一个清晰明了的解释。谢谢!
要将数据传递给您的组件,可以使用props
。有关props
的更多信息,请查看此处。而这里则是定义这些props
的好去处。
您可以像这样操作:
<example :userId="{{ Auth::user()->id }}"></example>
或者
<example v-bind:userId="{{ Auth::user()->id }}"></example>
然后在你的 Example.vue
文件中,你需要定义你的 prop。然后你可以通过 this.userId
访问它。
例如:
<script>
export default {
props: ['userId'],
mounted () {
// Do something useful with the data in the template
console.dir(this.userId)
}
}
</script>
@if(auth()->check())
<script>
window.User = {!! auth()->user() !!}
</script>
@endif
User
对象。调用组件,
<example :user-id="{{ Auth::user()->id }}"></example>
在组件中,
<script>
export default {
props: ['userId'],
mounted () {
console.log(userId)
}
}
</script>
https://laravel.com/docs/8.x/blade#blade-and-javascript-frameworks
渲染 JSON
有时你可能会将一个数组传递给视图,以便在JavaScript变量中初始化JSON。例如:
<script>
var app = <?php echo json_encode($array); ?>;
</script>
然而,与其手动调用json_encode,您可以使用@json Blade指令。@json指令接受与PHP的json_encode函数相同的参数。默认情况下,@json指令使用JSON_HEX_TAG、JSON_HEX_APOS、JSON_HEX_AMP和JSON_HEX_QUOT标志调用json_encode函数:
<script>
var app = @json($array);
var app = @json($array, JSON_PRETTY_PRINT);
</script>
<askquestionmodal :product="{{ $item->title }}"></askquestionmodal>
在控制台中仍然会出现错误,而不是显示HTML页面,我看到的是白屏。[Vue warn]: Error compiling template:
invalid expression: Unexpected identifier in
Coupling to connect 2 rods М14 CF-10
Raw expression: :product="Coupling to connect 2 rods М14 CF-10"
<askquestionmodal :product="'{{ $item->title }}'"></askquestionmodal>
现在,我的代码完全可用。
/components/askquestionmodal.vue
<template>
<div class="modal-body">
<p>{{ product }}</p>
</div>
</template>
<script>
export default {
name: "AskQuestionModal",
props: ['product'],
mounted() {
console.log('AskQuestionModal component mounted.')
}
}
</script>
<span hashid="{{ Auth::user()->id }}"></span>
,然后在Vue组件中添加以下代码:<script> export default { data: function () { return { hashid: '' } } } </script>
。你可以在任何地方使用console.log()打印出auth id。 - Hiren Gohel