【问题标题】:VueJS Extends Methods and DataVueJS 扩展方法和数据
【发布时间】:2017-01-14 23:19:30
【问题描述】:

我想扩展方法。示例:

Vue.extend({
    data: function () {
        return {
            fetcData: 'Test',
        }
    },
    methods: function(){
        return {
            modal: function(){ alert('Modal') },
        }
    }
});
Vue.extend({
    ....
});

我使用多个扩展。

// VueJS Instance
new Vue({
    el: 'html',
    data: {
        effect: true
    },
    methods: {
        xhrGet: function () {
            alert(this.fetcData); // Undefined
            this.modal(); // Undefined
        },
        xhrPost: function (event) {
            alert('xhrPost')
        }
    }
});

错误代码: this.fetchData 未定义。 this.modal 不是函数

【问题讨论】:

  • extend 用于创建组件。从您的代码中,我没有看到任何组件。

标签: vue.js vue-resource vue-component


【解决方案1】:

Vue.extend 返回一个新的 Vue 组件定义,稍后可以使用 new 关键字进行实例化,它不会更改全局 Vue 对象。因此,如果您想创建组件层次结构,请尝试:

var BaseComponent = Vue.extend({
  methods: {
    foo: function() { console.log('foo') }
  }
})

var MyComponent = BaseComponent.extend({
  methods: {
    bar: function() { 
      this.foo()
      console.log('bar')
    }
  }
})

let myComponentInstance = new MyComponent()

查看fiddle 以获取实时示例。

【讨论】:

  • 这与Vue.component('foo', {extends: bar ...有何不同
猜你喜欢
  • 2015-10-20
  • 2016-10-08
  • 1970-01-01
  • 2020-08-11
  • 2016-02-13
  • 2012-07-29
  • 1970-01-01
  • 2010-12-03
  • 2011-03-11
相关资源
最近更新 更多