VueJs+chrome-extension+element-ui天气预报的小插件

这篇具有很好参考价值的文章主要介绍了VueJs+chrome-extension+element-ui天气预报的小插件。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

这里通过chrome-extension + VueJs + element-ui来实现个天气预报的小插件,如下图:

VueJs+chrome-extension+element-ui天气预报的小插件

一、项目初始化、基础配置及相关插件安装

1.1 创建项目

        通过vue-cli脚手架3.0版本来创建项目,命令如下:

vue create demo-chrome-vue

默认选择是vue2.0语法

Successfully代表安装成功。

这里不是做web项目,所以删除vue-cli3脚手架的部分文件,删除文件如下:
src/main.js
src/components
src/App.vue

1.2 安装chrome-ext插件依赖

        项目创建成功后,通过指令:cd demo-chrome-vue进入项目,执行以下命令操作。

vue add chrome-ext

安装后,package.json的配置如下:

"devDependencies": {
	"@vue/cli-plugin-babel": "~5.0.0",
	"@vue/cli-plugin-eslint": "~5.0.0",
	"@vue/cli-service": "~5.0.0",
	"copy-webpack-plugin": "^4.6.0",
	"eslint": "^7.32.0",
	"eslint-plugin-vue": "^8.0.3",
	"vue-cli-plugin-chrome-ext": "0.0.5",
	"vue-template-compiler": "^2.6.14"
},

1.3 关闭eslint语法检测,方便开发

        找到vue.config.js文件,关闭lintOnSave即可。

module.exports = {
  pages: pagesObj,
  lintOnSave: false,	//关闭语法检测
  configureWebpack: {
    plugins: [CopyWebpackPlugin(plugins)]
  }
};

1.4 增加@type/chrome

        相关chrome api需要引入 “@type/chrome”增加chrome声明

        命令行如下:

npm install --save-d @types/chrome

1.5 图标修改

这里直接入在public目录了,public/icon.png。这样会直接生成到dist目录中。然后后manifest.production.json中配置即可,如下代码:

{
    "manifest_version": 2,
    "name": "Demo",
    "description": "通过chrome-extension + VueJs来实现天气预报的小插件",
    "version": "0.0.1",
    "browser_action": {
		"default_icon": "icon.png",	
        "default_popup": "popup.html"
    },
	"icons": {
		"16": "icon.png",
		"32": "icon.png",
		"48": "icon.png",
		"128": "icon.png"
	},
}

default_icon图标是显示在popup位置的图标,icons图表是显示在插件位置的.

1.6 element-ui安装

npm install --save element-ui

在popup目录中index.js中引入 :

import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css';
Vue.use(ElementUI);

二、axios请求

2.1 封装request.js

        在utils目录中,创建request.js请求,对axios进行封装,完善请求功能配置。代码如下:

import axios from 'axios'
import { Message, Loading } from 'element-ui'

axios.defaults.headers['Content-Type'] = "application/json;charset=utf-8";

const Service = axios.create({
  baseURL: "https://devapi.qweather.com",
  timeout: 30 * 1000
});

let loadingOption = {
  text: "加载中...",
  background: "rgba(0, 0, 0, 0)"
}, loading;

Service.interceptors.request.use(config => {
  loading = Loading.service(loadingOption);
  config.data = 'object'===typeof config.data?JSON.stringify(config.data):config.data;
  return config;
}, error => {
  loading.close();
  return Promise.reject(error);
})

Service.interceptors.response.use(response => {
  loading.close();
  if(response.status==200){
    return response['data'];
  }
  return Promise.reject(response);
}, error => {
  loading.close();
  return Promise.reject(error);
})

export default Service;

2.2 封装工具类

        在utils目录中,创建util.js文件,事前定义好日期格式化函数,代码如下:

const fillZero = _value => {
	return _value<10?'0'+_value:_value;
}

export const formatDate = (_date, _format) => {
	_format = 'undefined'===typeof _format||!_format?'YYYY-MM-DD':_format;
	let _newDate = new Date(_date),
			_values = {
				YYYY: _newDate.getFullYear(),
				MM: fillZero(_newDate.getMonth()+1),
				DD: fillZero(_newDate.getDate()),
				hh: fillZero(_newDate.getHours()),
				ii: fillZero(_newDate.getMinutes()),
				ss: fillZero(_newDate.getSeconds()),
				week: '星期'+'日一二三四五六'.charAt(_newDate.getDay())
			};
	for(var key in _values) _format = _format.replace(key, _values[key]);
	return _format;
}

三、免费天气接口平台

3.1 注册

地址:和风天气开发平台 ~ 高效强大的天气API,天气SDK和天气插件

        注册好地址后,并登录。另外调用接口时,请注意接口返回的状态码,如遇调用错误或返回对应错误码,也许是该接口需付费或已达上限。

3.2 创建应用

        登录后,选应用管理,点击“创建应用”,获取Key后,就可以通过key进行接口数据调用了。

3.3 天气图标

        在调用接口时,返回数据中的icon是以下图表对应的编码,通过拼接后则可以显示对应天气图标了。

        地址:天气图标 - RESOURCE | 和风天气开发平台

        可以通过git进行克隆本地,命令行:

git clone https://github.com/qwd/Icons.git

3.4 接口地址

实时天气
全国4000+个市县区和海外15万个城市实时天气数据,包括实时温度、体感温度、风力风向、相对湿度、大气压强、降水量、能见度、露点温度、云量等数据。
地址:实时天气 - API | 和风天气开发平台和风全球实时天气API,支持全国4000+个市县区和海外15万个城市实时天气数据,包括实时温度、体感温度、风力风向、相对湿度、大气压强、降水量、能见度、露点温度、云量等数据。https://dev.qweather.com/docs/api/weather/weather-now/

参数 描述
code

API状态码,具体含义请参考状态码

updateTime

当前API的最近更新时间

fxLink

当前数据的响应式页面,便于嵌入网站或应用

now.obsTime

数据观测时间

now.temp

温度,默认单位:摄氏度

now.feelsLike

体感温度,默认单位:摄氏度

now.icon

天气状况和图标的代码,图标可通过天气状况和图标下载

now.text

天气状况的文字描述,包括阴晴雨雪等天气状态的描述

now.wind360

风向360角度

now.windDir

风向

now.windScale

风力等级

now.windSpeed

风速,公里/小时

now.humidity

相对湿度,百分比数值

now.precip

当前小时累计降水量,默认单位:毫米

now.pressure

大气压强,默认单位:百帕

now.vis

能见度,默认单位:公里

now.cloud

云量,百分比数值。可能为空

now.dew

露点温度。可能为空

refer.sources

原始数据来源,或数据源说明,可能为空

refer.license

数据许可或版权声明,可能为空

逐天天气预报
全球城市未来15天天气预报,包括:日出日落、月升月落、最高最低温度、天气白天和夜间状况、风力、风速、风向、相对湿度、大气压强、降水量、降水概率、露点温度、紫外线强度、能见度等。

这里免费可以使用3天数据请求接口,7天及以上需要付费调用。

地址:逐天天气预报 - API | 和风天气开发平台和风天气预报API,提供全球城市未来15天天气预报,包括:日出日落、月升月落、最高最低温度、天气白天和夜间状况、风力、风速、风向、相对湿度、大气压强、降水量、降水概率、露点温度、紫外线强度、能见度等。https://dev.qweather.com/docs/api/weather/weather-daily-forecast/

参数 描述
code

API状态码,具体含义请参考状态码

updateTime

当前API的最近更新时间

fxLink

当前数据的响应式页面,便于嵌入网站或应用

daily.fxDate

预报日期

daily.sunrise

日出时间

daily.sunset

日落时间

daily.moonrise

月升时间

daily.moonset

月落时间

daily.moonPhase

月相名称

daily.moonPhaseIcon

月相图标代码,图标可通过天气状况和图标下载

daily.tempMax

预报当天最高温度

daily.tempMin

预报当天最低温度

daily.iconDay

预报白天天气状况的图标代码,图标可通过天气状况和图标下载

daily.textDay

预报白天天气状况文字描述,包括阴晴雨雪等天气状态的描述

daily.iconNight

预报夜间天气状况的图标代码,图标可通过天气状况和图标下载

daily.textNight

预报晚间天气状况文字描述,包括阴晴雨雪等天气状态的描述

daily.wind360Day

预报白天风向360角度

daily.windDirDay

预报白天风向

daily.windScaleDay

预报白天风力等级

daily.windSpeedDay

预报白天风速,公里/小时

daily.wind360Night

预报夜间风向360角度

daily.windDirNight

预报夜间当天风向

daily.windScaleNight

预报夜间风力等级

daily.windSpeedNight

预报夜间风速,公里/小时

daily.precip

预报当天总降水量,默认单位:毫米

daily.uvIndex

紫外线强度指数

daily.humidity

相对湿度,百分比数值

daily.pressure

大气压强,默认单位:百帕

daily.vis

能见度,默认单位:公里

daily.cloud

云量,百分比数值。可能为空

refer.sources

原始数据来源,或数据源说明,可能为空

refer.license

数据许可或版权声明,可能为空

3.5 创建api接口

在api目录中,创建api.js文件,在前面已讲了创建应用,把应用的KEY放到以下接口请求中即可。代码如下:

import Service from './request'

let getKey = () => {
	return {
		key: '创建应用的KEY'
	}
}

/**
 * 获取当前天气信息
 */
export const getCurrentWeather = params => {
	Object.assign(params, getKey())
	return Service.get('/v7/weather/now', {
		params: params
	})
}

/**
 * 获取3天天气信息
 */
export const get3DayWeather = params => {
	Object.assign(params, getKey())
	return Service.get('/v7/weather/3d', {
		params: params
	})
}

四、popup.html开发

1.html代码

        这里简单实现了常规天气显示状态,如需更多更详细的,可在基础上完善;接口不支持,或需要付费,请付费后再实现功能。

<template>
  <div class="main_app">
		<template v-if="isNetwork">
			<div class="top-box">
				<div class="table">
					<div class="cell left">
						<span v-if="currentWeatherInfo.windDir">{{currentWeatherInfo.windDir}} {{currentWeatherInfo.windScale}} 级</span>
					</div>
					<div class="cell right">
						<el-select size="mini" v-model="cityValue" placeholder="请选择" @change="cityChange">
							<el-option
								v-for="item in citys"
								:key="item.value"
								:label="item.label"
								:value="item.value">
							</el-option>
						</el-select>
					</div>
				</div>
			</div>
			<div class="weather-box">
				<div class="table">
					<div class="cell icon">
						<i class="qi-100"></i>
					</div>
					<div class="cell wd">
						<h3>{{currentWeatherInfo.temp}}°</h3>
						<p>{{currentWeatherInfo.text}}</p>
					</div>
					<div class="cell right">
						<div class="you">相对湿度:{{currentWeatherInfo.humidity}}%</div>
					</div>
				</div>
			</div>
			<div class="bottom-box">
				<div class="table">
						<div class="cell" v-for="(item, index) in weather3DayList" :key="index">
							<p>{{item.fxDate}}</p>
							<p>{{item.tempMin}}° ~ {{item.tempMax}}°</p>
							<p>
								<i :class="'qi-'+item.iconDay"></i>
							</p>
							<p class="clr-01">
								<span>{{item.textDay}}</span>
							</p>
						</div>
				</div>
			</div>
		</template>
		<template v-else>
			<div class="flex-date-box">
				<h4>{{currentDate}}</h4>
				<p v-if="week">({{week}})</p>
				<br />
				<p>当前未联网状态</p>
			</div>
		</template>
  </div>
</template>

2.css样式

刚把git克隆下来的项目代码中,打开font目录,复制fonts目录放到popup目录在,然后把qweather-icons.css放App目录中,并且打开qweather-icons.css文件,将fonts资源引入路径修改为当前目录结构,代码如下:

@font-face {
  font-family: "qweather-icons";
  src: url("./../fonts/qweather-icons.woff2") format("woff2"),
	url("./../fonts/qweather-icons.woff") format("woff"),
	url("./../fonts/qweather-icons.ttf") format("truetype");
}

以上操作完成后,则可以在style中引入样式文件了,样式代码如下:

<style>
@import './qweather-icons.css';			//引入天气样式

*{ margin: 0; padding: 0; }

.main_app {
  font-family: 'Avenir', Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  color: #2c3e50;
	width: 250px;
	height: 250px;
	padding: 10px;
	line-height: 1.5;
	background-size: cover;
	box-sizing: border-box;
	padding: 10px;
}

.flex-date-box{ width: 100%;height: 100%;display: flex;justify-content: center;align-items: center;font-size: 14px;color: #333;flex-direction: column; }
.flex-date-box h4{ font-size: 18px; }

.table{ width: 100%;display: table; }
.table .row{ display: table-row; }
.table .cell{ display: table-cell; vertical-align: middle; font-size: 12px; color: #333; }
.table .cell.left{ text-align: left; }
.table .cell.right{ text-align: right; }

.weather-box .table .cell{ vertical-align: bottom;padding: 10px 0; }
.weather-box .table .cell.wd, .weather-box .table .cell.icon{ width: 20px; white-space: nowrap; vertical-align: middle; }
.weather-box .table .cell.wd h3{ font-size: 30px;line-height: 1.3; }
.weather-box .table .cell.icon{ padding-left: 10px; padding-right: 10px; }
.weather-box .table .cell.icon i{ font-size: 42px; line-height: 1; }
.weather-box .table .cell.icon .wd h3{ font-size: 24px; }
.weather-box .table .cell.icon .wd p{ font-size: 16px; }
.weather-box .table .cell.right{ text-align: right; }
.weather-box .table .cell.right .you{ display: inline-block; line-height: 1; color: #94ce6f; border-left: 3px solid #94ce6f;padding-left: 8px; }

.weather-box .table.desc .cell{ padding: 5px 0; vertical-align: top; }

.bottom-box{ padding-top: 15px; margin-top: 10px; border-top: 1px solid rgba(204, 204, 204, 0.5); }
.bottom-box .table .cell{ vertical-align: middle; text-align: center;width: 33.33%; }
.bottom-box .table .cell i{ font-size: 20px; }
.bottom-box .table .cell .clr-01{ color: #94ce6f; }

.el-select{ width: 80px; }
.el-input__inner{ 
	background-color: transparent !important;
	border: 1px solid transparent !important;
	color: #333 !important;
}
.el-select .el-input .el-select__caret{ color: #333 !important; }
</style>

3.js部分

这里我们开始实现逻辑层功能,先引入天气接口调用函数及工具类,调用接口时判断当前接口是否畅通,如访问不了则当前网络不通,显示对应提示页面。
 

<script>
//引入接口函数
import { getCurrentWeather, get3DayWeather } from '../utils/api.js';
//引入工具类
import { formatDate } from '../utils/utils.js'
	
export default {
  name: 'app',
	data(){
		return {
			cityValue: "101010100",
			citys: [
				{ label: "北京", value: "101010100" },
				{ label: "上海", value: "101020100" },
			],
			isNetwork: false,
			currentDate: "",
			week: "",
			
			currentWeatherInfo: {},
			weather3DayList: [],
		}
	},
	created() {
		this.currentDate = formatDate(new Date(), "YYYY-MM-DD");
		this.week = formatDate(new Date(), "week");
		Promise.all([this.updateWeatcherInfo(), this.update3DayInfo()]).then(res => {
			this.isNetwork = true;
		}).catch(() => {
			this.isNetwork = false;
		})
	},
	beforeDestroy() {
		clearInterval(_handle)
	},
	methods: {
		/**
		 * 加载当前天气情况
		 */
		updateWeatcherInfo(){
			return getCurrentWeather({location: this.cityValue}).then(res => {
				if(res.code==200&&res['now']){
					this.currentWeatherInfo = res.now;
				}
			});
		},
		/**
		 * 加载3天内天气情况
		 */
		update3DayInfo(){
			return get3DayWeather({location: this.cityValue}).then(res=> {
				if(res.code==200&&Array.isArray(res['daily'])){
					this.weather3DayList = res.daily.map(item => {
						return {
							fxDate: item['fxDate'],
							tempMin: item['tempMin'],
							tempMax: item['tempMax'],
							iconDay: item['iconDay'],
							textDay: item['textDay'],
							iconNight: item['iconNight'],
							textNight: item['textNight']
						}
					});
				}
			});
		},
		/**
		 * 城市发生变化
		 */
		cityChange(e){
			this.updateWeatcherInfo();
			this.update3DayInfo();
		}
	}
}
</script>

写到这里,一个天气预报的chrome小插件就完成了。文章来源地址https://www.toymoban.com/news/detail-441787.html

到了这里,关于VueJs+chrome-extension+element-ui天气预报的小插件的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • element-ui 动态表单

    背景:朋友入职新公司,做项目重构,根据后端返回表单内容,动态生成表单,于是自己实现了下,哪里写的不好,欢迎各位提建议: 因为开关和多选框默认值是非空字符串,所以在created生命周期单独处理了下

    2024年02月11日
    浏览(73)
  • Element-ui 路由导航

    1.router数组 2.下载插件(解决div的bug) 3.创建sidebar-item 4.引用组件

    2024年02月12日
    浏览(33)
  • element-ui---头像上传

    样式 必选参数,上传的地址 是否显示已上传文件列表 文件上传成功的钩子 上传文件之前的钩子,参数为上传的文件,若返回 false 或者返回 Promise 且被 reject,则停止上传。 1.代码    可以看出在上传之前和上传完成后接收的两个参数对应相应的操作。 。

    2024年02月13日
    浏览(29)
  • element-ui如何导入

    Element UI是一个基于Vue.js的UI组件库,可以帮助您快速构建网站或应用。 要在您的Vue.js项目中使用Element UI,您需要进行以下步骤: 1.安装Element UI: 在命令行中运行以下命令,将Element UI安装到您的项目中: 或者,您也可以使用Yarn: 2.在您的Vue.js项目中导入Element UI: 在您的项

    2024年02月14日
    浏览(23)
  • element-ui消息组件

    目录 一、elementUI的消息组件 1、MessageBox 弹框:是模态框 2、Message 消息提示:非模态框,常用于主动操作后的反馈提示。 3、Notification 通知 二、Form表单: 1、基本结构  2、表单控件 三、Dialog组件 1、使用方法 1、MessageBox 弹框:是模态框 ​ (1)消息提示:当用户进行操作时

    2024年02月02日
    浏览(77)
  • 修改element-ui源码

    element-ui修改源码 1.首先,从git上拉取element的源码 2.安装依赖 npm install 3.修改 packages 中的源码,然后进行打包 npm run dist 4.找到你的项目中的 node_modules 包下的 element-ui 文件夹下的 lib 包,用你修改好后打包生成的 lib 包进行替换即可生效 下载链接在官网底部

    2024年02月11日
    浏览(30)
  • element-ui按需引入

    1、安装elment-ui组件库 官方网站 在项目的根目录下安装 element-ui 官方网页: 2、找到官方文档 官方网站 3、安装 babel-plugin-component 在你的项目根目录下运行该: 如: 4、修改 .babelrc 配置文件 vue-li 的 .babelrc 文件里为 babel.config.js 原来的 babel.config.js 文件: 修改后的 babel.config.j

    2024年02月04日
    浏览(48)
  • 【element-ui】Bug集合

    在el-dialog与el-select配合使用的时候,我们会发现el-select无法下拉,其实这问题就是下拉框层级不够和样式问题,那如何解决呢?下面就是解决方式。 这个直接说结论,你的form.radio 必须为空字符,才能使require生效! 解决方法:  没有设置最大高度,则有底边框,设置了则没有

    2024年02月06日
    浏览(22)
  • Vue与Element-UI

    Vue.js是一套用于构建用户界面的 渐进式 框架。 渐进式 是指,它既可以作为一个库使用,又可以作为一个框架使用 ,两个之间自如选择。库是不具有侵略性,在原有项目可以引入作为第三方依赖使用;框架是具有侵入性的,整个项目是用vue构建的。 前端技术栈的发展主要经

    2024年02月16日
    浏览(32)
  • element-ui 表格添加校验

      html片段     js片段 css片段

    2024年02月15日
    浏览(37)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包