gpt4 book ai didi

javascript - 如何将变量从 twig 传递到 vueJS(symfony 2.8 和 VueJS 2)

转载 作者:可可西里 更新时间:2023-11-01 01:12:37 26 4
gpt4 key购买 nike

我有一个 symfony 2.8 应用程序,我最近集成了 VueJs 2 作为我的前端框架,因为它提供了很大的灵 active 。我的应用程序不是单页的,我使用 symfony Controller 来呈现 View 。所有的 View 都包裹在一个基本的 Twig 布局中:

<!DOCTYPE html>
<html lang="{{ app.request.locale|split('_')[0] }}">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

</head>
<body>

<div id="app">
{% block body %} {% endblock %}
</div>

<script src="{{ asset('bundles/fosjsrouting/js/router.js') }}"></script>
<script src="/js/fos_js_routes.js"></script>

<script type="text/javascript" src="{{ asset('build/vendor-bundle.js') }}"></script>
<script type="text/javascript" src="{{ asset('build/vue-bundle.js') }}"></script>

</body>
</html>

我用 webpack 加载了大部分 JS,我所有的 vue 组件和 JS 依赖项都编译在 vendor-bundle.jsvue-bundle.js 中。我的 VueJs 实例如下所示:

import './components-dir/component.vue'
import './components-dir/component2.vue'

Vue.component('component', Component);
Vue.component('component2', Component2);

window.onload = function () {
new Vue({
el: '#app',
components: {}
});
};

我想将一些 php 变量从 Controller 传递到 vuejs 组件,但我无法让它工作。

一个非常简单的 Controller 示例如下所示:

    /**
* @Route("/contract", name="contract")
* @Method("GET")
*/
public function indexAction()
{
$paymentMethods = PaymentMethod::getChoices();

return $this->render('contracts/index.html.twig', [
'paymentMethods' => $serializer->normalize($paymentMethods, 'json'),
]);
}

所有的 html、css 和 js 都由 vueJs 处理。 Twig View 如下所示:

{% extends 'vue-base.html.twig' %}
{% block body %}
<contracts :paymentMethods="{{paymentMethods | raw}}"></contracts>
{% endblock %}

contracts.vue 组件如下所示:

<template>
<div>
<p>Hi from component</p>
</div>
</template>

<script>
export default {
data() {
return {}
},
props: ['paymentMethods'],
mounted: function () {
console.log(this.paymentMethods)
}
}
</script>
<style>
</style>

How can I pass the php variables as props to vueJs ?

在上面的例子中,我没有得到任何错误,但是属性没有传递给 vuejs。控制台日志打印 undefined。我希望能够做到这一点,因为我不想拥有 SPA,但我也想将一些变量从 symfony 传递到 vue,因为我不必发出额外的请求。

最佳答案

不是将 Twig 变量作为 Vue 属性的值传递:

<contracts :payment-methods="{{ twigVar}}"></contracts>

你可以使用 Twig 渲染整个:

<contracts {{ ':payment-methods="' ~ twigVar ~ '"' }}></contracts>

因此,您将避免 vue 和 twig 之间的分隔符冲突。

此外,由于该值直接来自 twig,它可能不会随时更改,因为它是在后端生成的——而不是在某些 vue 源中生成的——所以你不需要绑定(bind)它,只需像这样传递它:

<contracts payment-methods="{{ twigVar}}"></contracts>

关于javascript - 如何将变量从 twig 传递到 vueJS(symfony 2.8 和 VueJS 2),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49391988/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com