如何将Django变量传递给Vue prop

时间:2019-06-04 13:49:02

标签: javascript python django vue.js

我正在尝试将Django模板布尔变量传递给Vue组件。

在组件上,我将变量添加到道具中并指定了类型:

Vue.component('my-component', {
props: {
        id: {type: Number, required: true},
        static_url: {type: String, required: true},
        the_boolean_variable: {type: Boolean, required: true},
    },

创建组件:

<my-component v-bind:id={{ job.pk }}
              static_url="{{STATIC_URL}}"
              v-bind:the_boolean_variable={{ client.show_price }}>
</my-component>

我的第一个尝试是不绑定它,而只是传递client.show_price的值。 the_boolean_variable的值设置为字符串“ True”或“ False”,Vue抱怨说它接收的是字符串而不是布尔值。

Duckduckgo告诉我,我需要绑定非字符串值,所以我做了,但是现在我遇到了以下错误:“属性或方法“ True”未在实例上定义,但在渲染期间被引用。请确保此属性通过初始化属性,可以在data选项或基于类的组件中进行反应。请参阅:https://vuejs.org/v2/guide/reactivity.html#Declaring-Reactive-Properties。”检查the_boolean_variable的值显示为“未定义”。

我知道设置了{{client.show_price}}是因为如果我打印它,它会显示在页面上,并且如果我输入true而不是{{client.show_price}},就没有错误。

因此,我认为Vue混淆了它的表达方式?也许与Django模板语言冲突?任何帮助将不胜感激!

编辑:我在vue组件中添加了定界符:[“ <%”,“%>”],问题仍然存在。

1 个答案:

答案 0 :(得分:0)

哦..我发现这个丑陋的解决方法..

{% if client.show_price %}
<my-component v-bind:id={{ job.pk }}
              static_url="{{STATIC_URL}}"
              v-bind:the_boolean_variable=true>
</my-component>
{% else %}
<my-component v-bind:id={{ job.pk }}
              static_url="{{STATIC_URL}}"
              v-bind:the_boolean_variable=false>
</my-component>
{% endif %}

我认为,当考古学家找到我的代码时,他们会写出关于它的优美程度的歌曲。