我开始使用 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'
});
关于Symfony 4、Twig 和 VueJS - 重定向到 Vue 组件中的 Symfony 路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47724439/