【问题标题】:how to reference itself in a component in vuejs single file component如何在 vuejs 单文件组件中的组件中引用自身
【发布时间】:2017-04-18 13:09:29
【问题描述】:

这是我的代码:

 export default {
        data(){
            return {
                list: {}
            }
        },
        components: {
          listFields : ListFields
        },
        methods : {
            submitForm(data){
                let vm = this;
                console.log(vm);
                axios.post('/api/dashboard/lists/create', data)
                    .then(function (response) {
                        this.$router.push({path: 'show-list', params: {list_id: response.data.id}});
                    }).catch(function (error) {
                        console.log(error);
                    })
            }
        }
    }

问题在于,在我调用“this.$router.push”的方法内部,它会引发错误,因为 this 引用了该函数。但问题是我无法引用 vm,因为我正在导出组件。我怎么解决这个问题?

【问题讨论】:

  • 使用vm.$router,顺便说一句,我不明白为什么你不能将它引用到vm 以及它与导出的组件有什么关系?其他选项是在 axios 方法中使用箭头语法.then(response => { this.$router.push(//etc) })
  • 我实际上更喜欢使用 .bind(this) 让匿名函数知道上下文。
  • 您确定$router 已正确实例化吗?如果您将mounted 处理程序添加到您的组件并且console.log(this.$router) 它会返回一个值吗?如果没有,我们可以看看你是如何创建路由器的吗?
  • @BertEvans 当我在 created() 方法中调用它时 - 它返回正确的值

标签: vue.js


【解决方案1】:

您的回调函数不知道外部上下文。

要么使用 .bind(this) 要么声明 var that = this;

axios.post('/api/dashboard/lists/create', data)
  .then(function (response) {
    this.$router.push({path: 'show-list', params: {list_id: response.data.id}});
  }.bind(this)).catch(function (error) {
    console.log(error);
  })

var that = this;
axios.post('/api/dashboard/lists/create', data)
  .then(function (response) {
    that.$router.push({path: 'show-list', params: {list_id: response.data.id}});
  }).catch(function (error) {
    console.log(error);
  })

更新: 由于不知何故似乎没有任何效果,您可以尝试以下操作:为回调声明一个单独的方法

    methods : {
        submitForm(data){
            axios.post('/api/dashboard/lists/create', data)
                .then(this.onSuccess)
                .catch(function (error) {
                    console.log(error);
                })
        },
        onSuccess(response) {
           this.$router.push({path: 'show-list', params: {list_id: response.data.id}});
        }
    }

【讨论】:

  • 我确实在 submitForm 函数的顶部尝试过这个 - 但它抛出了一个错误 that.$router 没有推送功能。
  • 你的 console.log 为 vm.$router 返回什么?
  • 当我将它绑定到 submitform 函数中时,它返回 'undefined'
  • 当我从组件实例的 created(){} 方法运行它时,它会正确返回路由器实例
  • 你能在调用提交方法的地方添加代码吗?
猜你喜欢
  • 2017-03-12
  • 2022-07-04
  • 1970-01-01
  • 2021-05-25
  • 1970-01-01
  • 2019-08-10
  • 2021-08-01
  • 2018-06-28
  • 2019-05-13
相关资源
最近更新 更多