代码之家  ›  专栏  ›  技术社区  ›  Oliver Williams

VueJS在内部访问“导出默认值{}”,而不是定义的常量主应用程序

  •  2
  • Oliver Williams  · 技术社区  · 7 年前

    我的主应用程序页面中有以下代码,如果您使用VueJS(我现在开始使用),这可能很熟悉:

    //written in ES6
    const app = new Vue({
    el: '#app',
    data: function(){ return {
        query: {},
        requests: [],
        original: {},
        assignees: {},
        transiting: false,
        editing: false,
    }},
    created: function () {
        console.log(this.requests);   //this works
        console.log(app.requests);    //this also works
        this.doSomething('bar');
    },
    methods: {
        doSomething: function(arg){
            console.log('foo is a '+arg); //this works too
        }
    }
    });
    

    但是,我的组件JavaScript如下所示。这个 created 正在运行-我已经检查过了-但我似乎无法以相同的方式访问我的数据和方法,主要是因为我不熟悉“导出默认值{}”

    export default {
        name: 'request-tracking-calendar',
        data: {
                events: [
                    {
                        id: 10,
                        name: 'Boris',
                        ssn: '515860000',
                    },
                    {
                        id: 11,
                        name: 'Natasha',
                        ssn: '575860001',
                    },
                ]
        },
        created: function(){
            console.log('Updating events dynamically..'); 
            {
                //code omitted for clarity
                var xhr = new XMLHttpRequest();
                // etc.
                xhr.onload = function(a) {
                    if (xhr.status === 200) {
                        for (var i in xhr.response.data){
                        //DOESN'T work! not a function
    
          console.log(this.convertJSONToEvent(xhr.response.data[i])); 
                        }
                        console.log(this.events); //DOESN'T work
                    }
                };
                xhr.send();
            }
        },
        methods: {
            convertJSONToEvent(o){
                //do something to o..
                console.log('o was modified');
                return o;
            },
    

    如何让第二个示例中的上述调用在这里工作?一、 e.我将如何访问数据和方法?a是否可以同时声明变量和“导出默认值”,以便导出的默认值可以引用自身?

    1 回复  |  直到 7 年前
        1
  •  1
  •   Jacob Goh    7 年前

    您可以使用箭头功能 xhr.onload = (a)=>{} 来解决这个问题。

    正常功能 function(){} 绑定自己的 this 上下文,所以 不再引用Vue组件实例

    箭头函数没有自己的 所以 将自动从组件继承。

    如果不想使用箭头功能 (因为某些浏览器不支持它) ,您可以保存 先在变量中输入,然后在函数中使用它。

    var _this = this;
    xhr.onload = function(a) {
      if (xhr.status === 200) {
        for (var i in xhr.response.data) {
          // use _this
          console.log(_this.convertJSONToEvent(xhr.response.data[i]));
        }
        console.log(_this.events); // use _this
      }
    };