将 Laravel 变量传递给 Vue.js



我开始学习Vue.js。我想知道如何将刀片变量传递给 Vue.js?

喜欢

    return view('user.profile', ['locations' => $allLocations);

我可以通过 Vue.js 操纵它?

因为我计划实现一个动态下拉列表。实际上,有两个下拉菜单。因此,无论用户在第一个下拉列表中选择什么,第二个下拉列表将仅显示特定选项。

我已经尝试通过 1.( 实现它。隐藏一个元素,通过Javascript检索它,或者通过2。在页面加载后使用 HTTP AJAX 请求来初始化元素,但我发现这种方法有点混乱或有点占用资源。除了我上面提到的之外,还有其他实现吗?

谢谢!

您可以实现以下两种方法来传递变量:

  1. 使用 JSON 格式传递要查看的变量

    <script>
        var app = <?=json_encode($locations)?>
    </script>
    

    另请参阅:显示数据

  2. 通过 ajax 请求传递变量

    JS片段(可以放在Vue挂载/创建的方法中(

    $.ajax({
        method: 'GET',
        url: '/api/locations',
        success: function (response) {
            // response.locations
        }
    });
    

    API 路由(路由/api.php(

    Route::get('locations', 'LocationController@getLocations');
    

    位置控制器

    public function getLocations() {
        ...
        return response()->json($locations);
    }
    

最简单的方法是将其传递给您的视图(您拥有 vue 组件(,并将其作为道具接收。

 return view('user.profile', ['locations' => $allLocations]);

在您看来:

<your-component :data="{{$allLocations}}></your-component>

和 vue 组件,沿着这条线:

<template>
    --your HTML here--
</template>
<script>
    export default{
        props:['data'],
        data(){
            return{
                somethig:this.data.something
            }
        }
    }
</script>

这应该让你开始。 此外,我建议您在Laravel文档,Vue文档,Laracasts等中了解更多信息。

最好的编码给你!

你可以使用 Vue、Vuex、Axios

使用 .vue 时,我认为您不需要 .blade

使用 Vue + Laravel:

  1. 在 assets/js 中创建 App.vue

  2. 在 app.js 中导入 App.vue(使用 Laravel 5.6 的文件夹资源(

  3. 你想把刀片变量传递给 Vue.js?使用 JSON 或 XML。我爱杰森。所以在 Laravel 控制器中 -> 返回 json

  4. 在 App.vue 中,您可以使用 axios 调用 API(使用 Laravel 在控制器 + 路由中创建 1 个 API...(,并且您拥有所有变量,您想要:)

帮助它帮助你。谢谢

我尝试使用该方法检查我的订阅,发现它很方便:-

Vue.component('subscribe', require('./components/Subscribe.vue'));
const app = new Vue({
    el: '#app'
});

尝试转到链接:- 在此处输入链接说明

最新更新