我是Vue Js的初学者,刚刚和Symfony 4一起创建了Vue Js,我在Vue.js中遇到了表单渲染问题。
App.js
import Vue from 'vue'
import App from './Components/App.vue'
import PostForm from './Components/PostForm.vue'
new Vue({
el: '#app',
components: { App },
PostForm
})
Postform.vue
<template>
<div>
<h2 class="text-center">Post</h2>
<div id="post-form-holder" ref="form">
</div>
</div>
</template>
<script>
import axios from 'axoios'
export default {
async mounted(){
let {data} = await axios.get('/SymVue/post')
this.refs.form.innerHtml = data.form
}
}
</script>
调节器
/**
*
* @Route("/post", name="post.form")
*/
public function formAction(){
$form = $this->createForm(PostType::class);
$view = $this->renderView('vue/form.html.twig',[
'form' => $form->createView()
]);
return new Response('This is response');
}
在运行http://localhost:8000/SymVue/post时,浏览器会显示响应消息“This is response”
如果你运行http://localhost:8000/SymVue/post,那么显然你会在浏览器中看到响应。据我所知,应该有两种方法。在你的情况下。第一种方法将在浏览器中呈现表单,第二种方法将创建表单...
像这样....
/**
* @Route("/", name="vue", methods={"GET", "POST"})
*/
public function index()
{
return $this->render('vue/index.html.twig');
}
/**
*
* @Route("/post", name="post.form")
*/
public function formAction(){
$form = $this->createForm(PostType::class);
$view = $this->renderView('vue/form.html.twig',[
'form' => $form->createView()
]);
return new Response('This is response');
}
并且谈论你的app.js我猜你已经搞砸了,但无论如何你要做这样的事情,如果你想在PostForm.vue中渲染。在js文件夹中创建post.js并编写以下代码..
import Vue from 'vue'
import PostForm from './Components/PostForm.vue'
new Vue({
template: '<PostForm />',
components: { PostForm }
}).$mount('#postForm');
并在你的PostForm.vue(在你的代码中犯了一些拼写错误)
import axios from 'axios'
import 'babel-polyfill'
export default {
name: 'PostForm',
async mounted(){
let {data} = await axios.get('/SymVue/post')
this.$refs.form.innerHTML = data.form
}
}
现在回到你的vue / index.html.twig中的Twig Template
{% block body %}
<div id="postForm">
<PostForm />
</div>
{% endblock %}
{% block javascripts %}
<script src="{{ asset('build/postForm.js') }}"></script>
{% endblock %}
不要忘记在webpack.config.js中添加条目
.addEntry('postForm', './assets/js/post.js')
将呈现的模板用作响应主体。 :)
$view = $this->renderView('vue/form.html.twig',[
'form' => $form->createView()
]);
return new JsonResponse(['form' => $view]);
如果你想将VueJs与Symfony一起使用,我并不是建议你像以前的答案一样通过symfony传递html代码,你会搞乱应用程序模板并做一个额外的请求。您应该像往常一样在html / vue代码中创建表单并手动传递csrf代码。如果您仍想使用symfony生成表单,只需使用以下插槽传递它:
<some-vue-component>
<div slot="form">
{{ form(form) }}
</div>
</some-vue-component>
您还可以查看我为此类案例编写的small vue component,以便使用FOSRestBundle自动显示表单错误。您还可以使用连接器实现Synchronizer Token Pattern或任何其他保护类型。