1. vue-class-component
作用
用于将Vue中组件用类的方式编写。
Demo
1.先定义一个组件ComponentA:
1 <template> 2 <div> 3 <h3>Simple header {{getText}}</h3> 4 </div> 5 </template> 6 <script> 7 import Vue from 'vue' 8 import Component from 'vue-class-component' 9 10 @Component({ 11 props: { 12 name: String 13 } 14 }) 15 export default class SimpleHeader extends Vue { 16 // initial data 17 id = 'myId' 18 19 // computed 20 get getText () { 21 return `${this.name}(${this.id})` 22 } 23 } 24 </script> 25 <style> 26 </style>
2. 在App.vue中引用它
<template> <div> <div class="sc-width-full sc-height-full"> <Layout> <SimpleHeader ref="headerMenu" name="david"></SimpleHeader> <div class="ivu-layout ivu-layout-has-sider" style="height:100%;"> <Layout id="pageContainer"> <div> <Content id="pageContent"> <router-view></router-view> </Content> </div> </Layout> </div> </Layout> </div> </div> </template> <script> import Vue from 'vue' import Component from 'vue-class-component' import SimpleHeader from './simple-header.vue' @Component({ components: { SimpleHeader } }) export default class Index extends Vue { userName = null; userRole = null; created () { this.getUserInfo() } getUserInfo () { // getUserInfo } } </script> <style> .ivu-layout { height: 100%; } .ivu-layout.ivu-layout-has-sider { display: block; height: calc(100% - var(--header-height)); margin-left: 0.75rem; padding: 0.5rem 1.25rem; } </style>
效果:
可以看出,借用vue-class-component我们可以把组件写成class的模式,和面向对象非常像,可以很方便地实现继承和封装。
2. vue-property-decorator
作用
装饰器来简化书写
Demo
还是刚刚的例子,App.vue改成
<template> <div> <div class="sc-width-full sc-height-full"> <Layout> <SimpleHeader ref="headerMenu" name="david"></SimpleHeader> <div class="ivu-layout ivu-layout-has-sider" style="height:100%;"> <Layout id="pageContainer"> <div> <Content id="pageContent"> <router-view></router-view> </Content> </div> </Layout> </div> </Layout> </div> </div> </template> <script> import {Component, Vue} from 'vue-property-decorator' import SimpleHeader from './simple-header.vue' @Component({ components: { SimpleHeader } }) export default class Index extends Vue { userName = null; userRole = null; created () { this.getUserInfo() } getUserInfo () { this.$axios({ method: 'GET', url: `/user_info` }).then(res => { if (res && res.status === 200) { this.userName = res.data.userName this.userRole = res.data.userRole this.$store.commit('setUserName', res.data.userName) this.$store.commit('setRole', res.data.userRole) } else { } }).catch(e => { console.error(e) }) } } </script> <style> .ivu-layout { height: 100%; } .ivu-layout.ivu-layout-has-sider { display: block; height: calc(100% - var(--header-height)); margin-left: 0.75rem; padding: 0.5rem 1.25rem; } </style>
和vue-class-component的区别不是很大,只是统一从vue-property-decorator引用了。当然还是其他的差异,我们在今后vue+ts里体会。