針對Vue文檔中部分大家可能不會去研讀的內容,我做了個小總結,作為有經驗者的快餐,不是特別適合初學者,可能有不妥之處,希望大家多提建議。
節省代碼量的mixin
mixin概念:組件級可復用邏輯,包括數據變量/生命周期鉤子/公共方法,從而在混入的組件中可以直接使用,不用重復寫冗余邏輯(類似繼承)
使用方法:
在某一公共文件夾pub下創建mixin文件夾,其下創建mixinTest.js
const mixinTest = { created() { console.log(`components ${this.name} created`) }, methods: { hello() { console.log('mixin method hello') } }}export default mixinTest在組件中引用剛才的公共混入文件并使用
import mixinTest from '../pub/mixin/mixinTest.js'export default { data() { return { name: 'hello' } }, mixins: [mixinTest], methods: { useMixin() { this.hello() } }}ps: 若是使用Vue.mixin()這個方法,則會影響之后創建的所有Vue示例,慎用!
注意mixin的幾個特性:
slot內容分發
slot概念引入:Vue跟React在寫法上的不同就在于組件與子組件內部元素的組織上,在組件里面沒有children元素供我們訪問和展現(暫不考慮render函數),取而代之的API是slot
使用場景定義:
<template> <div id="app"> <self-component> <!--self-component表示自定義的組件--> <span>12345</span> <!--父組件里的嵌套標簽--> </self-component> </div> </template><script>export default { components: [selfComponent]}</script><!--self-component的組件模板--><template> <div> <button><slot></slot></button> </div></template><script>export default { // 只有子組件的模板里面有slot標簽,才能取到寫在自定義組件里面的標簽的渲染引用}</script>
新聞熱點
疑難解答
圖片精選