說說Vue.js組件
什么是組件:組件是Vue.js最強大的功能之一。組件可以擴展HTML元素,封裝可重用的代碼。在較高層面上,組件是自定義的元素,Vue.js的編譯器為它添加特殊功能。在有些情況下,組件也可以是原生HTML元素的形式,以is特性擴展。
vue組件有兩種,一種是全局組件,一種是局部組件。整個項目經常用到的用全局寫法,用到比較少的專供特定頁面用的使用局部組件。
one----全局組件引入寫法:在項目的main.js中:
第一種,在main.js直接寫template:' 模版字符串'
Vue.component('tab-home', { template: `<div>Home component</div>`})Vue.component('tab-posts', { template: `<div>Posts component</div>`})Vue.component('tab-archive', { template: `<div>Archive component</div>`})第二種,分別寫tab-home.vue Tab-Posts'.vue Tab-Archive'.vue然后import TabHome from ‘ Tab-Home.vue '
Vue.use( TabHome); // 自定義全局組件的時候需要Vue.use(); Vue.component('tab-home', TabHome)); //初始化組件two ----局部組件引入 ,寫在需要的引入的組件,如helloworldimport TabAa from './tab-aa.vue'import TabBb from './tab-bb.vue'import TabCc from './tab-cc.vue'export default {name: 'HelloWorld',components:{TabAa,TabBb,TabCc},three----動態組件(tab切換 使用:is="currentTabComponent")<template><><buttonv-for="tab in tabs"v-bind:key="tab"v-bind:class="['tab-button', { active: currentTab === tab }]"v-on:click="currentTab = tab">{{ tab }}</button><componentv-bind:is="currentTabComponent"class="tab"></component></div></template>export default {name: 'HelloWorld',components:{TabAa,TabBb,TabCc},data () {return {currentTab: 'Home',tabs: ['Home', 'Posts', 'Archive','Aa','Bb','Cc'],loginType:'username',msg: 'Welcome to Your Vue.js App'}},computed: {currentTabComponent: function () {return 'tab-'+this.currentTab.toLowerCase()}},樣式:.tab-button {padding: 6px 10px;border-top-left-radius: 3px;border-top-right-radius: 3px;border: 1px solid #ccc;cursor: pointer;background: #f0f0f0;margin-bottom: -1px;margin-right: -1px;}.tab-button:hover {background: #e0e0e0;}.tab-button.active {background: #e0e0e0;}.tab {border: 1px solid #ccc;padding: 10px;}總結
以上所述是小編給大家介紹的vue組件(全局,局部,動態加載組件)實例詳解,希望對大家有所幫助,如果大家有任何疑問歡迎給我留言,小編會及時回復大家的!
新聞熱點
疑難解答