欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

vue中使用typescript

程序员文章站 2022-07-14 20:33:25
...

vue中使用typescript
home.vue

<template>
  <div class="home">
    {{name2}}
    <div :class="color">
      名字:{{name}}
      <button @click="changeName">改变颜色</button>
    </div>
    <input v-model="name" />

    <HelloWorld title="标题" content="内容" />
  </div>
</template>

<script lang="ts">
import { Component, Watch, Vue } from "vue-property-decorator";
import HelloWorld from "@/components/HelloWorld.vue";

@Component({
  components: { HelloWorld }
})
export default class Home extends Vue {
  color: string = "red";
  name: string = "武器大师";

  // 相当于component
  get name2() {
    return this.name + 6666;
  }

  @Watch("name")
  private watchName(val: string) {
    console.log("名字发生了改变");
  }

  changeName(): void {
    if (this.color === "red") {
      this.color = "blue";
    } else {
      this.color = "red";
    }
  }
}
</script>
<style>
.red {
  color: red;
}
.blue {
  color: blue;
}
</style>

HelloWorld.vue

<template>
  <div class="hello">
    <h3>{{ title }}</h3>
    <p>{{content}}</p>
  </div>
</template>

<script lang="ts">
import { Component, Prop, Vue } from "vue-property-decorator";

@Component
export default class HelloWorld extends Vue {
  @Prop() private title!: string;
  @Prop() private content!: string;
}
</script>
<style>
.hello {
  width: 300px;
  height: 300px;
  background-color: pink;
  margin: 0 auto;
}
</style>
相关标签: TypeScript