Symfony 4、Twig 和 VueJS - 重定向到 Vue 组件中的 Symfony 路由

标签 symfony vue.js twig vuejs2

我开始使用 Symfony 4,将 Twig 模板和 VueJS 用于 UI 组件。

我在 .vue 文件中有一个非常基本的组件,用于列出任务,目前呈现一个基本表格。

// task-list.vue

<template>
    <div>
        <table class="table table-bordered table-striped">
            <thead>
            <tr>
                <th>
                    Task
                </th>
                <th>
                    Description
                </th>
                <th>
                    Completed?
                </th>
            </tr>
            </thead>
            <tbody>
            <tr v-for="task in parsedTasks">
                <td>
                    {{ task.title }}
                </td>
                <td>
                    {{ task.description }}
                </td>
                <td>
                    {{ task.completed ? 'Yes' : 'No' }}
                </td>
            </tr>
            </tbody>
        </table>
    </div>
</template>

<script>
    export default {
      name: 'task-list',
      props: {
        tasks: {required: true}
      },
      computed: {
        parsedTasks() {
          return JSON.parse(this.tasks);
        }
      },
    };
</script>

该组件注册在根JS文件中;

// assets/js/app.js

Vue.component('task-list', TaskList);

new Vue({
  el: '#app-root'
});

然后在 Twig 模板中使用;

// tasks/list.html.twig

...
<task-list tasks="{{ tasks | json_encode }}"></task-list>
...

我希望能够使用 path() Twig 函数,以便在单击任务列表中的一行时,将用户重定向到生成的路线/路径。如果 Vue 组件不在 Twig 文件中,这是否可能?

作为附带问题,是否有比 json 编码然后解析数据更好的方法将 Twig 变量传递给 Vue 组件?

最佳答案

主要有两种方法: 在后端生成 URL 并在 javascript 中使用它:

var route = "{{ path('blog_show', {'slug': 'my-blog-post'})|escape('js') }}";

https://symfony.com/doc/current/routing/generate_url_javascript.html

或者使用与 symfony 路由集成的 javascript 路由库,如 FOSJsRouting:

var url = Routing.generate('blog_show', {
    'slug': 'my-blog-post'
});

https://github.com/FriendsOfSymfony/FOSJsRoutingBundle

关于Symfony 4、Twig 和 VueJS - 重定向到 Vue 组件中的 Symfony 路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47724439/

相关文章:

symfony - 在 Controller 中获取 'Request' 对象的最佳方法是什么?

php - base.html.twig 中的自定义变量

html - 如何在 Victoire 生成的小部件中添加 HTML 属性

symfony - 使用 datafixtures 和 fosuserbundle 创建管理员用户

javascript - Div 内容可编辑,按 Enter 键时插入新元素

templates - 传递给嵌入模板的 Twig block

javascript - Vuetify 选择默认值

vue.js - 如何在 vue-i18n 中显示带小数点和不带小数点的货币

php - Symfony2+Twig,翻译中的变量返回 "A message must be a simple text"

php - 如何包装HTML代码而不在Twig中包含新文件?