vue-cli + typescript + vue-property-decorator

同一个坑可以掉一次也可以止步一次,但绝不可以掉进去第二次。

前期准备,安装node.js和npm,vue/cli
npm install -g @vue/cli   //安装vue/cli

vue ui  //启动vue/cli项目仪表盘

创建项目时勾选TypeScript,创建好的项目自动配置了TypeScript支持
包括声明文件shims-tsx.d.tsshims-vue.d.ts

cli.jpg

mixins混入

我理解的mixins混入,类似于用一个自定义的组件(以下简称子组件)封装对象的公共属性和方法,父组件引入子组件后以‘继承’的方式可以使用子组件的属性和方法。

// 子组件 MyMinins.ts  
import Vue from 'vue';
import Component from 'vue-class-component';

@Component  // 一定要用Component修饰
export default class MyMinins extends Vue {
  name: string = "Hello"
  sum(a: number, b: number) {
    return a + b
  }
}
//js一般写法
let mixin = {
  data () {
    return {

    }
  },
  created () {
    this.getBuList()
  },
  methods: {
    getBuList () {
      let that = this
      //逻辑
    },
  }
}
export default mixin;

须要使用混入的组件内import 引入MyMinins.ts, 注: export default class About extends mixins(myMixins)中的 default不能少,不能写成export class About extends mixins(myMixins)
混入的属性或者方法可以直接使用this.来访问

//about.vue
<template>
  <div class="about">
    <h1>This is an about page</h1>
    {{msg}}
  </div>
</template>
<script lang="ts">
import Component, { mixins } from 'vue-class-component'
import myMixins from '../components/MyMinins' //引入混入组件MyMinins
@Component
export default class About extends mixins(myMixins) {
  msg: string = ''
  created () {
    this.msg=this.name
    let count=this.sum(1, 2)
    console.log(count)
  }
}
</script>
//js一般写法
//import导入js,export default {}不变,只需使用mixins注册,类似于components注册组件,可直接调用mixins里面的方法
import optionMixin from '../../mixins/index';

export default {
  components: { subCrumbs },
  mixins: [optionMixin],
  data () {
    return {
    }
  }
}

浏览器展示 Hello
控制台输出 3

@Prop

 @Prop() private msg!: string;
 @Prop(Number) propA!: number;
 @Prop({default: 'default value'}) propB!: string;
 @propC([String, Boolean]) propC: string | boolean;

@Component 引入组件

import HelloWorld from "@/components/HelloWorld.vue";

@Component({
  components: {
    HelloWorld
  }
})

@Watch

  @Watch("wnewName") // 属性监听
  wnewName(val: number) {
    this.value = val;
  }

计算属性 computed

get phone() {
    //  计算属性    方法前添加get关键字
    return "http://xxxx.xxxx.com/";
  }

methods 方法组

// 不需要使用methods 包裹,直接在生命周期同级写就行
  add() {
    this.num += 1;
  }

@Emit 事件的监听与触发,

    this.emitTodo("world"); // 触发

  @Emit() 
  emitTodo(n: string) {
    console.log("hello" + " " + n);
  }
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容