如何在vuejs单个文件组件的组件中引用自身

时间:2017-04-18 13:09:29

标签: vue.js

所以这是我的代码:

 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);
                    })
            }
        }
    }

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

1 个答案:

答案 0 :(得分:0)

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

使用.bind(this)或声明var = 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}});
        }
    }