Laravel Vue.js-如何在axios URL中使用blade suntax
在我的Laravel+Vue.js SPA单页应用程序中,我使用axios作为HTTP客户端来发出POST请求。在Vue组件Register.Vue中,我有:Laravel Vue.js-如何在axios URL中使用blade suntax,laravel,vue.js,axios,laravel-blade,Laravel,Vue.js,Axios,Laravel Blade,在我的Laravel+Vue.js SPA单页应用程序中,我使用axios作为HTTP客户端来发出POST请求。在Vue组件Register.Vue中,我有: axios.post('@{{ route("register") }}', this.name, // the data to post { headers: { 'Content-type': 'ap
axios.post('@{{ route("register") }}',
this.name, // the data to post
{ headers: {
'Content-type': 'application/json',
}
})
.then(response => {
this.result = response.data.bpi
})
.catch(error => {
console.log(error)
this.errored = true
});
<body>
<div id="app"></div>
<script src="{{ asset('js/app.js') }}"></script>
</body>
但当发出请求时,Firfox浏览器控制台显示404错误,axios尝试发出请求的URL显示为错误http://127.0.0.1:8000/@%7B%7B%20路由%22从网络选项卡注册%22%20%7D%7D
如何在axios ajax请求中使用路由“注册”作为URL
编辑:
如果您想了解应用程序的体系结构,我将尝试在下面详细说明:
app.js文件包含:
window.axios = require('axios');
import router from './router';
import App from '../components/App.vue';
var app = new Vue({
el: '#app',
render: h => h(App),
router,
mount(){
console.log("Root instance mounted ");
}
});
import Register from '../components/Register.vue';
export default new VueRouter({
mode: 'history',
routes: [
{ path: '/register', component: Register, name: 'register' }
],
router.js文件包含:
window.axios = require('axios');
import router from './router';
import App from '../components/App.vue';
var app = new Vue({
el: '#app',
render: h => h(App),
router,
mount(){
console.log("Root instance mounted ");
}
});
import Register from '../components/Register.vue';
export default new VueRouter({
mode: 'history',
routes: [
{ path: '/register', component: Register, name: 'register' }
],
web.php有:
我的App.vue有:
在assets/views/app.blade.php中,我有:
axios.post('@{{ route("register") }}',
this.name, // the data to post
{ headers: {
'Content-type': 'application/json',
}
})
.then(response => {
this.result = response.data.bpi
})
.catch(error => {
console.log(error)
this.errored = true
});
<body>
<div id="app"></div>
<script src="{{ asset('js/app.js') }}"></script>
</body>
如果在.blade文件中,则只能使用blade语法 调用API时,必须静态设置此路由或其他路由 不建议:
或者,您可以在主刀片文件中定义js变量,然后在Register.vue文件中使用该变量。不幸的是,除非您直接在刀片模板中编写vue代码,否则无法在vue中使用刀片语法,这不是最佳做法。我发现有一件事很有用,那就是在google文档中写出我所有的Laravel API路由,这样在Vue中引用它们时就更容易参考。我希望这有帮助 如果没有.blade文件,就无法执行此操作。不支持vue组件动态使用laravel路由。但是您可以使用一些第三方软件包来实现这一点,比如Zigy
我不建议这样做。我完全同意,但这是绕过itAs程序员的一种方法,我们不应该简单地寻找一种方法来绕过它,我们应该寻找最干净的方法来编写它。“在谷歌文档中写出我所有的Laravel API路由”-你在这里如何使用谷歌文档?只需打开谷歌文档的空白页,列出你所有的Laravel API路由。这些文档实际上没有多大用途,不是吗?你在你的路由器文件中列出了所有这些吗?这只是一个偏好的问题。在谷歌文档中,它们可以更干净、更容易阅读。你可以做你喜欢做的事!如果有帮助的话,您介意将我的答案标记为top吗?vue组件位于app.blade.php中。请参阅'EDIT2'@IstiaqueAhmed,如果您使用的是刀片,您可以执行{!!路由'register'!!}。但根据您的代码,我假设您正在使用vue组件,并在vue组件中调用php路由“register”,这是行不通的。对于vue组件,您可以使用上述插件。@IstiaqueAhmed还可以尝试使用{!!route'register'!!}而不是{{route'register'}