我正在开发一个网页。我在这个网页上有一个登录表。我使用Django作为后端,使用VueJS作为前端。要使用Django提交表单,Django的要求是CSRF令牌。我目前可以使用{{ csrf_token }}向HTML显示CSRF令牌。
因为我使用的是VueJS,所以我也使用Vuetify来设计前端的样式。CSRF令牌对VueJS是不可见的,因为VueJS不能识别{{ csrf_token }}。
在网上搜索后,我发现了一些东西。我尝试使用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令牌的值可以被VueJS访问。
发布于 2019-05-13 21:33:24
哈罗德·哈德沃德医生
我不明白,但是你的组件被认为是错误的。
请尝试此代码
<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示例
发布于 2019-05-13 21:34:25
你不应该使用v-bind:csrf,因为当django呈现csrf_token时,它将是文字(例如,不是变量)。V-bind用于将对象绑定到组件属性中。所以要这样做:
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 %}https://stackoverflow.com/questions/56112848
复制相似问题