Vue - Extend

  • 824
  • 0
  • Vue
  • 2019-06-20

使用Extend來有效率的縮短程式碼,

如果不同template內有共同用到的data、filters、mounted等屬性,

可以抽出去做成extend,template在擴充extend之後,自己還是可以額外宣告這些屬性

先看以下的Code

兩個不同的元件,內容其實很像,唯一的不同是兩個使用不同的 template

var childOne = {
  props: ['item'],
  data: function() {
    return {
      data: {},
      extendData: '這段文字是 extend 得到'
    }
  },
  template: '#row-component',
  filters: {
    dollarSign: function (n) {
      return `$ ${n}`
    },
    currency: function(n) {
      return n.toFixed(2).replace(/./g, function(c, i, a) {
          return i && c !== "." && ((a.length - i) % 3 === 0) ? ',' + c : c;
      });
    }
  },
  mounted: function() {
    console.log('Extend:', this)
  }
}

var childTwo = {
  props: ['item'],
  data: function() {
    return {
      data: {},
      extendData: '這段文字是 extend 得到'
    }
  },
  template: '#row-component-two',
  filters: {
    dollarSign: function (n) {
      return `$ ${n}`
    },
    currency: function(n) {
      return n.toFixed(2).replace(/./g, function(c, i, a) {
          return i && c !== "." && ((a.length - i) % 3 === 0) ? ',' + c : c;
      });
    }
  },
  mounted: function() {
    console.log('Extend:', this)
  }
}

第一步,先將childOne改為Extend

// extend 是基礎建構的概念
// 宣告一個新的變數,使用Vue.extend的語法
var newExtend = Vue.extend({
    // 將原本在childOne裡面的屬性貼過來
	data: function() {
		return {
			data: {},
			extendData: '這段文字是 extend 得到'
		}
	},
	template: '#row-component',
	filters: {
		dollarSign: function(n) {
			return `$ ${n}`
		},
		currency: function(n) {
			return n.toFixed(2).replace(/./g, function(c, i, a) {
				return i && c !== "." && ((a.length - i) % 3 === 0) ? ',' + c : c;
			});
		}
	},
	mounted: function() {
		console.log('Extend:', this)
	}
})


var childOne = {
    // 只留下屬性:props,其他的屬性通通都搬到newExtend裡面去
	props: ['item'],
	// 新增屬性extends,後面接的就是剛剛宣告的變數newExtend
	extends: newExtend
}

概念上,childOne就是把newExtend改為基底,並延伸使用

接著可以來修改childTwo

把childTwo所有的屬性都刪除,只留下props以及template,

childTwo跟childOne唯一的差異就是使用的template

var childTwo = {
	props: ['item'],
	template: '#row-component-two',
	extends: newExtend
}

基底的物件newExtend裡面已經有一個mounted(下圖1),接著在childTwo也新增一個mounted(下圖2)

接著來看執行結果

可以看到執行到childTwo的時候,他會先執行基底元件的mounted,在執行自己的mounted。

 

如果我在childTwo裡面新增屬性data

看一下執行結果

childOne的產生的物件

childTwo產生的物件

可以看到childTwo擁有自己新增的獨立資料,可繼承原有的資料結果,並新增自己的資料結構。

但是如果childTwo新增的data內屬性名稱跟基底的相同,則會覆蓋掉原有的屬性內容。