vue如何使用TypeScript语法

一、新建项目

vue create vue-ts-admin

按步骤开始安装,安装过程中选择TypeScript,vuex,路由router; 使用npm run serve启动项目

  1. 在vue中书写ts的必备插件!
  2. vue-class-component 强化 Vue 组件,使用装饰器语法使 Vue 组件更好的跟TS结合使用。 vue-property-decorator在 vue-class-component 的基础上增加了更多与 Vue 相关的装饰器,使Vue组件更好的跟TS结合使用。
  3. npm i vue-class-component -s-d
  4. npm i vue-property-decorator -s-d

二、ts写vue单文件写法

2.1 如何在Data双向绑定值

  • js写法
<template>
  <div class="hello">
    <h1>{{msg}}</h1>
  </div>
</template>
<script>
export default {
   data() {
    return {
      msg: "",
    };
  },
}
</script>
  • ts写法
<template>
  <div class="hello">
    <h1>{{msg}}</h1>
  </div>
</template>
<script src="ts">
import { Component, Vue, } from "vue-property-decorator";
@Component
export default class Home extends Vue {
  //注意点:3.public是公用的意思,可省略;没有data,return,直接放要绑定的值
  public msg!: number | string;
  // msg!: number | string;
}
</script>

2.2 如何引入子组件及组件传值

  • js写法
<template>
  <div class="hello">
    <MenuBar :setMsg="msg"/>
  </div>
</template>
<script>
import MenuBar from "../components/MenuBar.vue";
export default {
  props: {
    // 父组件的值
    fatherMsg: {
      type: String
    }
  },
  components: {
    MenuBar
  },
  data() {
    return {
      msg: "",
    };
  },
}
</script>
  • ts写法
<template>
  <div class="hello">
    <MenuBar :setMsg="msg" />
  </div>
</template>
<script src="ts">
import { Component, Vue, } from "vue-property-decorator";
import MenuBar from "../components/MenuBar.vue";
@Component({
  components: {
    MenuBar
  },
})
export default class Home extends Vue {
  // 父组件的传递过来的值
  @Prop() private fatherMsg!: string;
  //传递给子组件的值
  public msg!: number | string;
}
</script>

2.3 methods方法

  • js写法
<template>
  <div class="hello">
    <h1>{{count}}</h1>
    <button class="btn" @click="addCount">add</button>
  </div>
</template>
<script>
var data = {name: "小明",age: 18};
export default {
   data() {
    return {
      count: 0,
    };
  },
  methods: {
    addCount() {
      return this.count++;
    }
  }
}
</script>
  • ts写法
<template>
  <div class="hello">
    <h1>{{count}}</h1>
    <button class="btn" @click="addCount">add</button>
  </div>
</template>
<script  src="ts">
import { Component, Vue, } from "vue-property-decorator";
var data = {name: "小明",age: 18};
@Component
export default class Home extends Vue {
  public count: number = 0;
  //   方法也是直接写到外层
  addCount(): number {
    return this.count++;
  }
}
</script>

2.4 计算属性(computed)和监听属性(watch)

  • js写法
<template>
  <div class="hello">
  <h1>计算属性:{{countChange}},结果+2:{{watchMsg}}</h1>
    <button class="btn" @click="addCcountChange">计算属性:add</button>
    <h1>监听:{{count}},结果+1:{{watchMsg}}</h1>
    <button class="btn" @click="addCount">监听add</button>
  </div>
</template>
<script>
var data = {name: "小明",age: 18};
export default {
   data() {
    return {
      count: 0,
      watchMsg: ""
    };
  },
  watch: {
    count: {
      handler(newVal, oldVal) {
        if (newVal < 10) {
          this.watchMsg = "我是数字" + newVal;
        } else {
          this.watchMsg = "我会继续增长";
        }
      },
      immediate: true
    },
    watchMsg: {
      handler(newVal, oldVal) {
        console.log(newVal);
      },
      immediate: true
    }
  },
  computed: {
    countChange: {
      get() {
        return this.count;
      },
      set(val) {
        this.count = val + 1;
      }
    }
  },
  methods: {
   addCcountChange() {
      return this.countChange;
    },
    addCount() {
      return this.count++;
    }
  }
}
</script>
  • ts写法
<template>
  <div class="hello">
    <h1>计算属性:{{countChange}},结果+2:{{watchMsg}}</h1>
    <button class="btn" @click="addCcountChange">计算属性:add</button>
    <h1>监听:{{count}},结果+1:{{watchMsg}}</h1>
    <button class="btn" @click="addCount">监听add</button>
  </div>
</template>
<script  src="ts">
// 注意1.导入Watch
import { Component, Vue,Watch } from "vue-property-decorator";
var data = {name: "小明",age: 18};
@Component
export default class Home extends Vue {
  public count: number = 0;
  public watchMsg: string = "开始";
    //   计算属性
  get countChange(): number {
    return this.count;
  }
  set countChange(val) {
    this.count = val + 1;
  }
  // 注意2. 监听多个就导入多个Watch,命名自定义 clgMsg(newVal: string)
  @Watch("count")
  Count(newVal: number) {
    if (newVal < 10) {
      this.watchMsg = "我是数字" + newVal;
    } else {
      this.watchMsg = "我会继续增长";
    }
  }
  @Watch("watchMsg")
  clgMsg(newVal: string) {
    console.log(newVal);
  }
   //   方法
  addCcountChange(): number {
    return this.countChange++;
  }
  addCount(): number {
    return this.count++;
  }
}
</script>

2.5 路由vue-Router及路由守卫

  1. 安装导入路由—— mian.ts
import Vue from 'vue'
import App from './App.vue'
import store from './store'
import router from './router'
//1.导入组件
import Component from 'vue-class-component'
Vue.config.productionTip = false

// 1.全局的路由守卫,js和ts的写法一致;
// 2.组件内路由守卫,如果要在组件内部使用路由监听,路由钩子beforeRouteEnter,beforeRouteLeave,beforeRouteUpdate不生效。所以在此注册;
Component.registerHooks([
  'beforeRouteEnter',//进入路由之前
  'beforeRouteLeave',//离开路由之前
  'beforeRouteUpdate'
])

new Vue({
  store,
  router,
  render: h => h(App)
}).$mount('#app')
  1. 路由index文件写法—— router/index.ts
import Vue from 'vue';
import Router from 'vue-router';
import stickyNotePage from '../page/stickyNotePage.vue';

export default new Router({
    // history模式
    mode: 'history',
    base: process.env.BASE_URL,
    routes: [
        // 常规模块加载
        {
            path: '/',
            name: 'stickyNotePage',
            component: stickyNotePage,
        },
        // 路由懒加载写法
        {
            path: '/hello',
            name: 'hello',
            component: () => import(/* webpackChunkName: "hello" */'../page/HelloWorld.vue'),
        },
        {
            path: '/learn',
            name: 'learn',
            component: () => import(/* webpackChunkName: "learn" */'../page/learn.vue'),
        },
    ],
})
Vue.use(Router);
  1. 在页面中如何使用路由守卫
    全局的路由守卫,js和ts的写法一致;
// 全局守卫
import router from './router'
router.beforeEach((to, from, next) => {    
    console.log(to.path);
    next()    
})
// 全局后置钩子
router.afterEach((to,from)=>{
  alert("after each");
})
  1. 组件内路由守卫
<template>
  <div class="hello">
    <h1>{{count}}</h1>
  </div>
</template>
<script  src="ts">
import { Component, Vue, } from "vue-property-decorator";
@Component
export default class Home extends Vue {
  public count: number = 0;
   // 进入路由触发
  beforeRouteEnter(to: any, from: any, next: () => void): void {
    console.log("beforeRouteEnter111");
    next();
  }
  beforeRouteUpdate(to: any, from: any, next: () => void): void {
    console.log("beforeRouteUpdate111");
    next();
  }
  // 离开路由触发
  beforeRouteLeave(to: any, from: any, next: () => void): void {
    console.log("beforeRouteLeave111");
    next();
  }
}
</script>

2.6 axios请求数据

2.6.1 main.ts

import axios from 'axios'
Vue.prototype.$axios = axios;

2.10.2 单页使用

<template>
  <div class="hello">
    axios请求
  </div>
</template>
<script  src="ts">
import { Component, Vue,} from "vue-property-decorator";
import axios from "axios";
// 写在@Component内
@Component
export default class Home extends Vue {
   created(): void {
    const url1 = "https://www.foobar.com/my-app/user/add";
    axios.get(url1, { params: { type: "js" } }).then((res: any) => {
      console.log(res);
    });
    // 使用vue代理
    const url2 = "/my-app/user/add";
    axios.get(url2, { params: { type: "Ts" } }).then((res: any) => {
      console.log(res);
    });
  }
}
</script>

你可能感兴趣的:(typescript)