【问题标题】:Vue.js - Props are undefined in component methodVue.js - 组件方法中未定义道具
【发布时间】:2017-06-24 12:47:05
【问题描述】:

我开始将 Vue.js 集成到一个 Django 项目(多页应用程序)中。

首先,我尝试创建一个简单的注销组件,该组件将 POST 到注销路由。路由的端点来自 Django 的 url 模板标签。

组件方法中的端点属性是undefined。尽管它在组件模板中可用。我做错了什么?


Django 模板

<div id="logout">
    <logout endpoint="{% url 'account_logout' %}"
            csrf_token="{{ csrf_token }}"></logout>
</div>
{% render_bundle 'logout' %}

logout.js

import Vue from 'vue'
import Logout from './Logout.vue'


new Vue({
    el: '#logout',

    components: {
        Logout
    }
});

Logout.vue

<template>
    <div>
        <span class="logout-link"
              @click="performLogout">

            Logout
        </span>
    </div>
</template>


<script>
    export default {
        name: 'logout',

        props: [
            'csrf_token',
            'endpoint'
        ],

        data () {
            return {
            }
        },

        methods: {
            performLogout: event => {
                console.log(`Endpoint: ${this.endpoint}`); // <-- undefined
                // this.$http.post(this.endpoint);
            }
        }
    }
</script>


<style>
    .logout-link {
        padding: 3px 20px;
        cursor: pointer;
    }
</style>

【问题讨论】:

    标签: django vue.js vue-component


    【解决方案1】:

    this 存在范围界定问题。

    this 在你的方法中没有指向 vue 实例。这就是为什么您不能使用 this.endpoint 访问 endpoint 属性的原因。

    试试这样:

    methods: {
        performLogout(event) {
            console.log(`Endpoint: ${this.endpoint}`); 
                    // this.$http.post(this.endpoint);
        }
    } 
    

    【讨论】:

    猜你喜欢
    • 2017-07-08
    • 2020-06-09
    • 2017-09-12
    • 2023-04-08
    • 1970-01-01
    • 2023-03-05
    • 2020-08-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多