typescript在vue中的入门案例代码demo

目录
  • 搜索框searchBox.vue
  • 首页Home.vue
  • 热门城市 popularCity.vue
  • 天气 weather.vue
  • getWeather.ts

使用技术栈vue2+typescript+scss入门练手项目,天气预报demo,需要的朋友可以参考下。整体的实现思路比较简单,页面也只有一个,包含三部分,搜索框、热门城市和天气预报,组件库用的是ElementUI。

搜索框searchBox.vue

<template>
  <div id="search">
    <el-input
      placeholder="请输入内容"
      suffix-icon="el-icon-search"
      v-model="city"
      @change="enter"
      @input="edit"
    >
    </el-input>
  </div>
</template>

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

@Component({
  components: {},
})
export default class searchBox extends Vue {
  city = "";

  @Emit("sendCity")
  enter(value: string): string {
    //在输入框失去焦点或用户按下回车时触发(会导致一些bug!!!)
    console.log("按下回车,搜索地是:" + value);
    return value;
  }

  edit(value: string | number): void {
    console.log("正在输入中......" + value);
  }
}
</script>

这里不写@component注解,会导致组件中的数据和处理方法不是响应式的,刚开始写的时候根本没有意识到这个问题,点击页面中的输入框el-input组件根本没反应,一直觉得是逻辑或者element有问题,后来查了资料才知道是@component没有写。searchBox子组件需要把自己的数据传给weather组件,两个组件为兄弟关系,通信的话可以借助父组件Home组件。在ts中,组件间的数据传递,通过@Emit,子组件将数据发送出去,父组件通过函数接收,而父组件与子组件通信,通过@Prop。

首页Home.vue

<template>
  <div class="home">
    <img alt="Vue logo" src="../assets/logo.png" />
    <searchBox @sendCity="sendCity" />
    <popularCity @popularCity="clickCity" />
    <weather :searchCity="city" :popularCity="city" />
  </div>
</template>

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

@Component({
  components: {
    searchBox,
    popularCity,
    weather,
  },
})
export default class Home extends Vue {
  city = "";

  sendCity(city: string): void {
    //搜索框组件向home组件传值
    this.city = city;
  }

  clickCity(city: string): void {
    //热门城市传值
    this.city = city;
  }
}
</script>

热门城市 popularCity.vue

<template>
  <div id="city">
    <div v-for="(item, index) in message" :key="index">
      <el-button class="box-city" type="text" @click="clickCity(item)">{{
        item
      }}</el-button>
    </div>
  </div>
</template>

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

@Component({
  components: {},
})
export default class searchBox extends Vue {
  message = ["北京", "上海", "深圳", "成都", "重庆", "武汉", "南京"];

  @Emit("popularCity")
  clickCity(city: string): string {
    console.log("点击热门城市:" + city);
    return city;
  }
}
</script>

<style lang="scss" scoped>
@import "../style/index.scss";
#city {
  width: 40%;
  @include box-row-flex(center);

  .box-city {
    width: 10%;
    font-style: italic;
    color: $text-color;
    font-size: $font-size;
  }
}
</style>

这个没有什么好说的,主要就是进行了scss的一些尝试,比如@mixin

天气 weather.vue

<template>
  <div id="weather">
    <div v-for="(item, index) in weatherArr" :key="index">
      <el-card class="box-card">
        <div slot="header" class="clearfix">
          <span>{{ city }}</span>
        </div>
        <div class="content">
          <div class="type">{{ item.type }}</div>
          <div class="temp">
            {{ item.low | temperatureFilter }} ~
            {{ item.high | temperatureFilter }}
          </div>
          <div class="time">{{ item.date }}</div>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script lang="ts">
import weather from "../interface/IWeather";
import getWeather from "../utils/getWeather";
import { Vue, Component, Prop, Watch } from "vue-property-decorator";

@Component({
  components: {},
  filters: {
    //过滤器
    temperatureFilter: (value: string): string => {
      return value.substring(2);
    },
  },
})
export default class searchBox extends Vue {
  @Prop({
    type: String,
    default: "",
  })
  searchCity!: string;

  city = "西安";
  weatherArr: Array<weather> = [];

  @Watch("searchCity")
  async handleWatch(value: string): Promise<void> {
    console.log("搜索框或热门城市传入的地区是:" + value);

    const res = await getWeather(value);
    console.log(res);
    if (res.status == 1000) {
      this.city = value;
      this.weatherArr.length = 0; //清空当前数组存入的数据
      this.weatherArr.push(...res.weather);
    } else if (res.status == 1002) {
      this.$message({
        message: res.desc as string,
        type: "error",
      });
    }
  }

  async created(): Promise<void> {
    const res = await getWeather("西安");
    if (res.status == 1000) {
      this.weatherArr.push(...res.weather);
    } else if (res.status == 1002) {
      this.$message({
        message: res.desc as string,
        type: "error",
      });
    }

    console.log(res);
  }
}
</script>

这里是整个demo的核心,负责接收其他组件的数据,发送请求,获取天气数据。

先来说一下其他组件传递数据,上面说了父子组件通信通过@Prop,这里用了@Watch检测数据变化,如果点击了某个热门城市或者搜索框按下回车键,会发送数据到这部分,数据来了就通过axios发送请求,获取天气数据。这里关于发送网络请求的部分,进行了封装。

同时,根据接口的返回数据写interface,这里为了展示数据(同时为了根据不同的返回码status来提示不同的消息),创建接口IWeather,主要用来抽象天气数据,IFiveWeather用来抽象接口返回形式(接口的代码就不在此展示)

getWeather.ts

import axios from "axios";

//获取某地的天气
async function getWeather(city: string): Promise<IFiveWeather> {
  const weatherArr: IFiveWeather = {
    status: 0,
    weather: [],
  };
  try {
    const res = await axios.get(
      `http://wthrcdn.etouch.cn/weather_mini?city=${city}`
    );

    const status: number = res.data.status;

    switch (status) {
      //输入城市错误的返回码
      case 1002:
        weatherArr.status = 1002;
        weatherArr.desc = res.data.desc;
        weatherArr.weather = [];
        break;
      //数据返回成功
      case 1000:
        weatherArr.status = 1000;
        weatherArr.weather.push(...res.data.data.forecast);
    }
  } catch (error) {
    console.log("天气接口出错啦:" + error);
  }

  return weatherArr;
}

export default getWeather;

到此这篇关于typescript在vue中的入门案例代码demo的文章就介绍到这了,更多相关typescript入门demo内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!

(0)

相关推荐

  • TypeScript与JavaScript的区别分析

    目录 TypeScript优势 TypeScript 与 JavaScript 的区别 TypeScript基本语法 TypeScript原始类型 1.字符串 2.数字 3.布尔值 4.Symbol原始类型 5.静态类型检测 TypeScript引用类型 1.数组 2.数组类型(Array) 3.元组类型(Tuple) 4. any 5. unknown 6. void.undefined.null 7. never 8. object 小结 TypeScript是微软开发的一个开源的编程语言,

  • typescript难学吗?前端有必要学?该怎么学typescript

    目录 什么是 TypeScript TypeScript 的流行趋势 TypeScript 的优势和收益是什么 TypeScript 与 JavaScript 对比表格 环境配置 国际惯例 Hello World tsconfig.json 与 Webpack 集成 结语 TypeScript代码与 JavaScript 代码有非常高的兼容性,无门槛,你把 JS 代码改为 TS 就可以运行.如果没有接触过强类型的编程语言,导致他们认为学习TS需要定义各种类型,还有一些新概念等等,会增加学习成本.

  • typescript快速上手的进阶类型与技术

    目录 类型别名 字符串字面量类型 元组 枚举 类 类的概念 TypeScript 中类的用法 参数属性 readonly 抽象类 类的类型 类与接口 泛型 泛型类 泛型参数的默认类型 声明合并 函数的合并 接口的合并 本文讲述了typescript开发的一些高级的类型与技术,算是对于基础知识点的补充,具体内容包括:比如元组.枚举类.接口.泛型相关概念等.虽说是进阶,但是内容不算多也并不难理解. 类型别名 类型别名用来给一个类型起个新名字. type Name = string; type Nam

  • Typescript是必须要学习吗?如何学习TS全栈开发

    目录 TS的全面性 TS的必学性 如何学习TS 学习经历 第一步学习ES6 学习React 学习Electron 学习Taro和React Native 学习Nestjs 学习CLI构建 推荐给大家 总结 Typescript目前在前端,网站,小程序中的位置基本无可替代,同时也可以构建完美的CLI应用.在移动,桌面,后端方面,性能不是要求很高的情况下完全可以胜任,并且在区块链,嵌入式,人工智能方面也开始茁壮成长. TS的全面性 目前来说前端基本是React,Vue,Angular这三框架占据主流

  • JavaScript Typescript基础使用教程

    目录 简介 安装 安装命令 使用原因 TypeScript类型概述 JS原有的类型 TS新增的类型 类型别名 泛型 简介 typescript是微软公司开发的开源编程语言,Type+Javascript(type是类型,在js的基础上添加了类型支持) 简称:ts,是Javascript的超集 安装 node.js或者我们的浏览器,他只认识js代码,不认识ts代码,所以我们需要把我们的ts转换为我们的js代码,然后进行运行操作 安装命令 npm i -g typescript yarn globa

  • typescript在vue中的入门案例代码demo

    目录 搜索框searchBox.vue 首页Home.vue 热门城市 popularCity.vue 天气 weather.vue getWeather.ts 使用技术栈vue2+typescript+scss入门练手项目,天气预报demo,需要的朋友可以参考下.整体的实现思路比较简单,页面也只有一个,包含三部分,搜索框.热门城市和天气预报,组件库用的是ElementUI. 搜索框searchBox.vue <template> <div id="search"&g

  • VUE中的无限循环代码解析

    代码如下所示: <template> <div id=""> <ul v-for="(item,index) in listaaa"> <li v-if='dealFun(item.cdate,index)'>{{item.cdate}}</li> </ul> </div> </template> <script> export default { name:

  • vue 中的keep-alive实例代码

    Vue 实现组件信息的缓存 当我们在开发vue的项目过程中,避免不了在路由切换到其他的component再返回后该组件数据会重新加载,处理这种情况我们就需要用到keep-alive来缓存vue的组件信息,使其不再重新加载. 一.在app.vue里 <keep-alive> <router-view></router-view> </keep-alive> 但是这种情况会对所有的组件进行缓存,不能达到单个组件缓存的效果. 那么我们给部分组件加上,实现方法如下:

  • vue中的过滤器实例代码详解

    过滤器 1.过滤器规则 Vue.js 允许你自定义过滤器,可被用于一些常见的文本格式化.过滤器可以用在两个地方: 双花括号插值{{}}和  v-bind 表达式 (后者从 2.1.0+ 开始支持).过滤器应该被添加在 JavaScript 表达式的尾部,由"管道"符号指示: <!-- 在双花括号中 --> {{ name | Upper }} <!-- 在 `v-bind` 中 --> <div v-bind:id="martin | Upper

  • 浅析Vue中拆分视图层代码的5点建议

    一.框架的定位 框架通常只是一种设计模式的实现,它并不意味着你可以在开发中避免所有分层设计工作. SPA 框架几乎都是基于 MVC 或 MVVM 设计模式而建立起来的,这些模式都只是宏观的分层设计,当代码量开始随着项目增大而增多时,问题就会越来越多.许多企业内部的项目仍然在使用 angularjs1.X ,你会发现许多 controller 的体积大到令人发指,稍有经验的团队会利用好 angularjs1 构建的 controller , service , filter 以及路由和消息机制来完

  • Vue中使用vux配置代码详解

    一.根据vux文档直接安装,无需手动配置 npm install vue-cli -g // 如果还没安装 vue init airyland/vux2 my-project // 创建名为 my-project 的模板 cd my-project // 进入项目 npm install --registry=https://registry.npm.taobao.org // 开始安装 npm run dev // 运行项目 二.想在已创建的Vue工程里引入vux组件 <1>. 在项目里安装

  • 封装一下vue中的axios示例代码详解

    在vue项目中,和后台交互获取数据这块,我们通常使用的是axios库,它是基于promise的http库,可运行在浏览器端和node.js中.他有很多优秀的特性,例如拦截请求和响应.取消请求.转换json.客户端防御cSRF等.所以我们的尤大大也是果断放弃了对其官方库vue-resource的维护,直接推荐我们使用axios库.如果还对axios不了解的,可以移步axios文档. 安装 npm install axios; // 安装axios 好了,下面开始今天的正文. 此次封装用以解决: (

  • Python中sorted()用法案例代码

    目录 Python中sorted()用法 sorted() 作为 Python 内置函数之一,其功能是对序列(列表.元组.字典.集合.还包括字符串)进行排序. sorted() 函数的基本语法格式如下: list = sorted(iterable, key=None, reverse=False) 其中,iterable 表示指定的序列,key 参数可以自定义排序规则:reverse 参数指定以升序(False,默认)还是降序(True)进行排序.sorted() 函数会返回一个排好序的列表.

  • vue中格式化时间过滤器代码实例

    本文实例为大家分享了vue格式化时间过滤器的具体代码,供大家参考,具体内容如下 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <script src="https://unpkg.com/vue"></script> <

  • vue中使用rem布局代码详解

    1.npm i amfe-flexible 2.import 'amfe-flexible' 然后再,安装postcss-px2rem插件 npm i postcss-px2rem 在package.json中配置 "postcss": { "plugins": { "autoprefixer": {}, "postcss-px2rem": { "remUnit": 26.7 } } } 在vue项目中使用

随机推荐