0

我正在使用 vue-resource 对资源(例如文章标签)执行 CRUD。对于 CUD,我需要发送一个 csrf 令牌和数据。我的服务器端代码接受自定义 HTTP 标头“X-CSRF-TOKEN”并检查其值。

我为每个标签条目制作一个标签组件。csrf 令牌来自根实例并绑定到标签组件,如下所示:

<tr v-for="tag in tags" is="tag" :tag="tag" :token="token"></tr>

这是模板

<template id="tag-template">
    <tr>
    <td>@{{ tag.id }}</td>
    <td>@{{ tag.name }}</td>
    <td>
        <button type="button" class="btn btn-xs btn-outline green">Edit</button>
        <button type="button" class="btn btn-xs btn-outline red" @click="deleteTag(tag,token)">Delete</button>
    </td>
    </tr>
</template>

根据 vue-resource 文档,我可以像这样设置自定义标头: Vue.http.headers.common['X-CSRF-TOKEN'] = token; 我还可以在组件设置中预设此标头。

下面的代码是我想要实现的:

Vue.component('tag', {
    props: ['tag', 'token'],
    template: '#tag-template',
    methods: {
        deleteTag: function (tag, token) {
            // I don't want to repeat this line in my updateTag(), createTag() etc.
            Vue.http.headers.common['X-CSRF-TOKEN'] = token;
            this.$http.delete('/api/tags/' + tag.id).then(
                function () {
                    vm.tags.$remove(tag);
                },
                function () {}
             );
         }
    },
    http: {
        headers: {
            // how to reference/use prop 'token' here?
            'X-CSRF-TOKEN': 'token from prop list'
        }
    }
});

问题是,如何在其他组件选项中使用 prop?

谢谢你。

4

1 回答 1

0

不要使用道具,在您的情况下没有必要。

如果你真的想使用 prop,你可以把它们放在一个全局变量中。

于 2016-07-13T07:43:14.053 回答