我正在开发一个网页。 我在这个网页上有一个登录表单。 我正在使用Django作为后端,而VueJS则用于前端。 要使用Django提交表单,Django的要求是CSRF令牌。 我目前可以使用{{ csrf_token }}
将CSRF令牌显示为HTML。
因为我正在使用VueJS,所以我也使用Vuetify来设计前端的风格。 VUEJS看不到CSRF令牌,因为VueJS无法识别{{ csrf_token }}
但HTML确实如此。
在互联网上研究后,我找到了一些东西。 我尝试使用v-bind将CSRF令牌从HTML提供给VueJS,但不幸的是v-bind的值未定义。 但是,如果我转到我的源代码(Ctrl + U),我可以看到CSRF Toekn确实有效,但VueJS无法识别它。
例:
<div id="LoginApp">
<WJLogin
v-bind:csrf="8cl33zQ8pYXXEMVCoSsqIzaFgQkLh6WYXqsQMN4z9X4oGkSGN8Thz922jQ19aG4B"
v-bind:hello="world">
</WJLogin>
</div>
当我使用从VueJS到VueJS的v-bind时,这可以工作,但从HTML到VueJS不起作用
这是login.html
<div id="LoginApp">
<WJLogin
:csrf="{{csrf_token}}"
:hello="world">
</WJLogin>
</div>
这是WJLogin.vue
export default
{
props: {
csrf: String,
hello: {
type: String,
default: "defaultValue"
},
},
..............
............
我希望CSRF Token的值可以访问VueJS。
哈罗德哈德瓦德博士,
我不明白你的组件是错的。
请试试这个代码
<div id="LoginApp">
<WJLogin
:csrf="csrf_token"
:hello="world">
</WJLogin>
</div>
<template>
<!-- If it is fixed -->
<div>{{ $props.csrf }}</div>
</template>
<script>
export default {
name: 'W3Login',
props: {
csrf: String
},
// If it will be change.
computed: {
token() {
return this.$prop
}
}
methods: {
If using in any method.
x() {
...
this.$prop.csrf
...
}
}
}
</script>
示例链接JsFiddle
你不应该使用v-bind:csrf
因为当django渲染csrf_token
,它将是文字的(例如不是变量)。 V-bind
用于将对象绑定到组件prop中。 这样做:
index.html的:
<div id="LoginApp">
<wjlogin
csrf="{{ csrf_token }}"
hello="world">
</wjlogin>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
{% verbatim %}
<script>
Vue.component('wjlogin', {
template: `<div>{{ csrf }}<br/>{{ hello }}</div>`,
name: 'wjlogin',
props: {
csrf: String,
hello: {
type: String,
default: "defaultValue"
},
},
});
new Vue({el: '#LoginApp'})
</script>
{% endverbatim %}