【问题标题】:Reference/Use property in other options of the same Vue component在同一个 Vue 组件的其他选项中引用/使用属性
【发布时间】:2016-11-15 13:41:18
【问题描述】:

我正在使用 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;我也可以在组件设置中预设这个header。

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

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?

谢谢。

【问题讨论】:

    标签: vue.js vue-resource


    【解决方案1】:

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

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

    【讨论】:

    • 那么如何在我的组件中引用根实例的数据字段,特别是在其他选项对象中?我尝试了'X-CSRF-TOKEN': vm.token 之类的方法,但没有运气。 (我将根实例分配给变量 vm。)
    • 如前所述,做全局变量
    猜你喜欢
    • 2018-03-05
    • 2018-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多