编程开源技术交流,分享技术与知识

网站首页 > 开源技术 正文

05-Vue脚手架安装axios、echarts等插件(二)

wxchong 2024-09-16 07:06:56 开源技术 8 ℃ 0 评论

1、安装ElementUI

Element,一套为开发者、设计师和产品经理准备的基于 Vue 2.0 的桌面端组件库。官方推荐使用 npm 的方式安装,因为它能更好地和 webpack 打包工具配合使用。具体的安装命令如下:

# npm 安装
npm i element-ui -S

# OR
npm install element-ui --save

执行完上述命令后,在package.json文件中,会增加了element-ui的引用,具体内容如下:

{
  "name": "default",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "serve": "vue-cli-service serve",
    "build": "vue-cli-service build"
  },
  "dependencies": {
    "core-js": "^2.6.5",
    "element-ui": "^2.13.2",
    "vue": "^2.6.10"
  },
  "devDependencies": {
    "@vue/cli-plugin-babel": "^3.8.0",
    "@vue/cli-service": "^3.8.0",
    "vue-template-compiler": "^2.6.10"
  }
}

但是仅仅引入进来,还不能直接使用,还需要在main.js文件中,引入element-ui才能在各个组件中使用,具体代码如下:

// file:main.js
import Vue from 'vue'
//--1
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'

import App from './App.vue'

//--2
Vue.use(ElementUI)

new Vue({
  el: '#app',
  render: h => h(App)
})

2、安装axios

既然vue是前后端分离的,那么前端和后端的数据交换,就需要一个js库来实现,在这里我们选择的是axios,安装命令如下:

npm install axios --save

安装完成后,要想使用axios库,也需要在main.js文件中增加如下配置代码:

// file:main.js
import Vue from 'vue'
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
//--1
import axios from 'axios'
import App from './App.vue'

//--2
axios.defaults.baseURL="http://localhost:8080";
Vue.prototype.$http = axios

Vue.use(ElementUI)

new Vue({
  el: '#app',
  render: h => h(App)
})

axios的请求可以使用下面的范例:

  • 异步模式:
    axios
      .get('https://api.coindesk.com/v1/bpi/currentprice.json')
      .then(response => {
        this.info = response.data.bpi
      })
      .catch(error => {
        console.log(error)
        this.errored = true
      })
      .finally(() => this.loading = false)

同步模式:

//使用 asyns/await 
async getHistoryData (data) {
 try {
   let res = await axios.get('/api/survey/list/', {
     params: data
   })
   this.tableData = res.data.result
   this.totalData = res.data.count
 } catch (err) {
   console.log(err)
   alert('请求出错!')
 }
}

3、安装vue-router

如果在创建项目的时候没有选择vue的路由插件,这就需要手动安装了,安装命令如下:

npm install vue-router

# OR
npm install vue-router --save

安装完插件之后,需要在main.js中引入vue-router,具体代码如下:

// file:main.js
import Vue from 'vue'
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
import axios from 'axios'
import App from './App.vue'
//--1
import router from './router'

//挂在到vue#app
Vue.prototype.$http = axios
// 配置请求的根路径
axios.defaults.baseURL = 'http://192.168.48.1:9001/'

Vue.use(ElementUI)

new Vue({
  el: '#app',
  //--2
  router,
  render: h => h(App)
})

在组件中增加路由占位符:

<!-- file:App.vue -->
<template>
  <div id="app">
	  <!-- 路由占位符 -->
	  <router-view></router-view>
  </div>
</template>

<script>
export default {
  name: 'App'
}
</script>

<style>
#app {
  font-family: Helvetica, sans-serif;
  text-align: center;
}
</style>

加上上面的路由占位符后,就可以实现vue各个组件页面的切换了。还有一步很重要,那就是创建路由守卫,这个步骤需要在项目的根目录下创建router目录,然后在该目录创建index.js文件,具体代码如下:

//file:router/index.js
import Vue from 'vue'
import Router from 'vue-router'
import Login from '../components/Login.vue'
import Main from '../components/Main.vue'

Vue.use(Router)

const router = new Router({
  routes: [
    {
      path: '/',
      name: 'Login',
      component: Login
    },
	{
	  path: '/Login',
	  name: 'Login',
	  component: Login
	},
	{
	  path: '/Main',
	  name: 'Main',
	  component: Main
	},
  ]
})

// 挂载路由导航守卫
router.beforeEach((to, from, next)=>{
	console.log("to="+to.path)
	console.log("from="+from.path)
	// to 要访问的路径
	// from 从哪个页面而来
	// next 是一个函数,表示放行
	// next() 放行, next('/Login')强制跳转
	if(to.path === '/Login') return next()
	// 获取token
	let userinfo = window.sessionStorage.getItem("userinfo")
	if(!userinfo) {
		return next({path:'/Login'})
	}
	console.log("userinfo1="+userinfo)
	let uu = JSON.parse(userinfo)
	//let uu = JSON.stringify(userinfo)
	console.log("username="+uu.name)
	next()
})

export default router

4、安装echarts

ECharts 是百度贡献的一个使用 JavaScript 实现的开源可视化库,涵盖各行业图表,满足各种需求,应用非常广泛,具体安装命令如下:

# 安装依赖
npm install echarts -S

# OR
npm install echarts --save

和其他插件的安装一样,需要在main.js中引入echarts,具体代码如下:

// main.js
import Vue from 'vue'
import App from './App.vue'

import echarts from 'echarts'
Vue.prototype.$echarts = echarts

Vue.config.productionTip = false

new Vue({
  render: h => h(App),
}).$mount('#app')

使用echarts和在普通页面没有太大区别,具体代码如下:

<template>
	<div id="myChart" :style="{width: '300px', height: '300px'}"></div>
</template>

<script>
export default {
  name: 'hello',
  data () {
    return {
      msg: 'Welcome to Your Vue.js App'
    }
  },
  mounted(){
    this.drawLine();
  },
  methods: {
    drawLine(){
        // 基于准备好的dom,初始化echarts实例
        let myChart = this.$echarts.init(document.getElementById('myChart'))
		// 准备数据
		let option = {
            title: { text: '在Vue中使用echarts' },
            tooltip: {},
            xAxis: {
                data: ["衬衫","羊毛衫","雪纺衫","裤子","高跟鞋","袜子"]
            },
            yAxis: {},
            series: [{
                name: '销量',
                type: 'line',
                data: [5, 20, 36, 10, 10, 20]
            }]
        };
        // 绘制图表
        myChart.setOption(option);
    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>

</style>

5、网上开源的vue的中后台

https://github.com/d2-projects/d2-admin.git
https://github.com/PanJiaChen/vue-element-admin.git
https://github.com/iview/iview-admin.git
https://github.com/epicmaxco/vuestic-admin.git
https://github.com/taylorchen709/vue-admin.git
https://github.com/lin-xin/vue-manage-system.git

Tags:

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表