Vue-cli(Vue脚手架)挂载Element-ui和axios方法

挂载Element-ui

1 . npm安装:使用npm下载Element-ui包

npm i element-ui -S

2 . 在main.js文件中添加如下代码:

//引入Element-ui
import Element from 'element-ui'
import "element-ui/lib/theme-chalk/index.css"

//Vue对象使用Element-ui
Vue.use(Element);

//在new Vue中添加组件
new Vue({
  el: '#app',
  router,
  components: {App, Element},
  template: '<App/>'
})

挂载axios

  1. npm安装:使用npm下载axios包
npm i axios
npm i --save axios vue-axios

2 . 在main.js文件中添加如下代码:

//引入axios
import axios from 'axios'
import VueAxios from 'vue-axios'

//定义$axios(可以不写,在组件中直接使用axios)
Vue.prototype.$axios= axios;

//Vue对象使用axios
Vue.use(axios);

//在new Vue中添加组件
new Vue({
  el: '#app',
  router,
  components: {App, axios},
  template: '<App/>'
})

3 .在组件中使用(以post请求为例):

  • 定义了$axios的情况下:
this.$axios.post("/user/login",{
    username:"xxx",
    password:"xxx"
}).then(function(res) {
    console.log(res);
}).catch(function(res) {
    console.log(res);
})
  • 未定义$axios的情况下:
axios.post("/user/login",{
    username:"xxx",
    password:"xxx"
}).then(function(res) {
    console.log(res);
}).catch(function(res) {
    console.log(res);
})
原文地址:https://www.cnblogs.com/lzb1234/p/11268028.html