Vue 的 class 组件介绍(vue-property-decorator)

 基于TS, vue-class-component 类组件的基本结构 

<script lang="ts">
import { Vue, Component } from "vue-property-decorator"
import { LocaleMessageObject } from "vue-i18n"
import { Prop } from "vue-property-decorator"
import { CommonObject } from "@/models/common"
import { State, Mutation } from "vuex-class"
import { Watch } from "vue-property-decorator"

// @Component 装饰器可以使类成为 Vue 组件
// ArticleDetails class will be a Vue component
@Component({
  name: "ArticleDetails",
  filters: {}
})
export default class ArticleDetails extends Vue {
  // Prop
  // 注意:属性的ts类型后面需要加上undefined类型;或者在属性名后面加上!,表示非null 和 非undefined
  // 的断言,否则编译器会给出错误提示;
  //@Prop 是告诉 Vue xxx 不是 data 是 prop
  //Number 是告诉 Vue xxx 运行时是个 Number 类型
  //number | undefined 是告诉 TS xxx 的编译时类型
  @Prop(Number) xxx: number | undefined;
  @Prop({ default: {}, required: true })
  listing!: CommonObject

  // Data
  texts = this.$t("dashboard-page") as LocaleMessageObject

  // Computed
  get saveBtnAble() {
    console.log("Computed")
  }
  // vuex state
  @State("currentBrandId", { namespace: "Brand" })
  currentBrandId!: number | string
  @State("activedMenu", { namespace: "Menu" })
  activedMenu!: Menu | { name: "" }

  // Watch
  @Watch("currentBrandId")
  curBrandIdChange(newV: number | string) {
    // 业务代码
  }

  // Mutation
  @Mutation("updateActivedMenu", { namespace: "Menu" })
  updateActivedMenu!: Function

  // life hooks
  async beforeMount() {
    console.log("beforeMount")
  }

  // Methods
  _onClickDashboard() {
    this.$emit("_onClickDashboard")
    this.updateActivedMenu()
  }
  _onClickClose() {
    this.$emit("_onClickDashboard")
  }
}
</script>

JS 对象的普通 vue 组件的基本结构 

// 使用 JS 对象的普通 vue 组件
<script lang="ts">
import Vue from "vue"
import { mapState } from "vuex"

export default Vue.extend({
  // components
  components: {},
  filters: {},
  // props
  props: {
    nav: {
      type: Object as () => any,
      default: () => {}
    }
  },
  // Data
  data() {
    return {}
  },
  // computed
  computed: {
    ...mapState("global", ["navBars"]),
    navData(): any {
      const { _, navBars, nav } = this
      const id = _.get(nav, "id")
      return _.get(navBars, id, {})
    }
  },

  // watch
  watch: {
    actived(newV) {
      console.log(newV)
    }
  },

  // life hook
  mounted() {},

  // methods
  methods: {
    handleRedirect(category: any) {
      // 业务代码
      this.$store.dispatch("test")
      this.$store.dispatch("commit")
    }
  }
})
</script>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值