03.vue-ajax、vue UI 组件库

vue-ajax

vue 项目中常用的 2 个 ajax 库

  • vue-resource: vue 插件, 非官方库, vue1.x 使用广泛
  • axios: 通用的 ajax 请求库, 官方推荐, vue2.x 使用广泛

vue-resource 的使用

示例代码


// 引入模块
import VueResource from 'vue-resource' 
// 使用插件
Vue.use(VueResource)
// 通过 vue/组件对象发送 ajax 请求 
this.$http.get('/someUrl').then((response) => {
    // success callback
    console.log(response.data) 
   //返回结果数据
 },
 (response) => {
   // error callback
   console.log(response.statusText)
   //错误信息 
})

axios 的使用

示例代码

// 引入模块
import axios from 'axios'
// 发送 ajax 请求 
axios.get(url)
.then(response => {
console.log(response.data) // 得到返回结果数据
})
.catch(error => {
console.log(error.message)
 })

搜索示例代码

/*main.js*/
/*
入口JS
 */
import Vue from 'vue'
import VueResource from 'vue-resource'
import App from './App.vue'

// 声明使用插件(安装插件)
Vue.use(VueResource) // 所有的vm和组件对象都多了一个属性: $http, 可以通过它的get()/post()发ajax请求

// 创建vm
/* eslint-disable no-new */
new Vue({
  el: '#app',
  components: {App}, // 映射组件标签
  template: '<App/>' // 指定需要渲染到页面的模板
})

/*App.vue*/

<template>
  <div class="container">
    <Search></Search>
    <UsersMain></UsersMain>
    <!--<users-main></users-main>-->
  </div>
</template>

<script>
  import Search from './components/Search.vue'
  import Main from './components/Main.vue'

  export default {
    components: {
      Search,
      UsersMain: Main
    }
  }
</script>

<style>

</style>

/*Search.vue*/

<template>
  <section class="jumbotron">
    <h3 class="jumbotron-heading">Search Github Users</h3>
    <div>
      <input type="text" placeholder="enter the name you search" v-model="searchName"/>
      <button @click="search">Search</button>
    </div>
  </section>
</template>

<script>
  import PubSub from 'pubsub-js'
  export default {
    data () {
      return {
        searchName: ''
      }
    },

    methods: {
      search () {
        const searchName = this.searchName.trim()
        if(searchName) {
          // 分发一个search的消息
          PubSub.publish('search', searchName)
        }
      }
    }
  }
</script>

<style>

</style>

/*Main.vue*/

<template>
  <div>
    <h2 v-show="firstView">请输入关键字搜索</h2>
    <h2 v-show="loading">请求中...</h2>
    <h2 v-show="errorMsg">{{errorMsg}}</h2>
    <div class="row" v-show="users.length>0">
      <div class="card" v-for="(user, index) in users" :key="index">
        <a :href="user.url" target="_blank">
          <img :src="user.avatarUrl" style='width: 100px'/>
        </a>
        <p class="card-text">{{user.username}}</p>
      </div>
    </div>
  </div>
</template>

<script>
  import PubSub from 'pubsub-js'
  import axios from 'axios'
  export default {
    data () {
      return {
        firstView: true, // 是否显示初始页面
        loading: false, // 是否正在请求中
        users: [], // 用户数组
        errorMsg: ''  //错误信息
      }
    },

    mounted () {
      // 订阅消息(search)
      PubSub.subscribe('search', (message, searchName) => { // 点击了搜索, 发ajax请求进行搜索

        // 更新数据(请求中)
        this.firstView = false
        this.loading = true
        this.users = []
        this.errorMsg = ''

        // 发ajax请求进行搜索
        const url = `https://api.github.com/search/users?q=${searchName}`
        axios.get(url)
          .then(response => {
            // 成功了, 更新数据(成功)
            this.loading = false
            this.users = response.data.items.map(item => ({
              url: item.html_url,
              avatarUrl: item.avatar_url,
              username: item.login
            }))
          })
          .catch(error => {
            // 失败了, 更新数据(失败)
            this.loading = false
            this.errorMsg = '请求失败!'
          })




      })
    }
  }
</script>

<style>
  .card {
    float: left;
    width: 33.333%;
    padding: .75rem;
    margin-bottom: 2rem;
    border: 1px solid #efefef;
    text-align: center;
  }

  .card > img {
    margin-bottom: .75rem;
    border-radius: 100px;
  }

  .card-text {
    font-size: 85%;
  }
</style>

vue UI 组件库

下载 Mint UI

  • 下载: npm install --save mint-ui

实现按需打包

  • 下载 npm install --save-dev babel-plugin-component

  • 修改 babel 配置

"plugins": ["transform-runtime",["component", [
   {
      "libraryName": "mint-ui",
      "style": true 
   }
]]]

mint-ui 组件分类

  • 标签组件
  • 非标签组件

使用 mint-ui 的组件

//index.html
 <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no" />
    <link rel="stylesheet" href="/static/css/bootstrap.css">
    <title>vue_demo</title>
    <script src="https://as.alipayobjects.com/g/component/fastclick/1.0.6/fastclick.js"></script>
    <script>
      if ('addEventListener' in document) {
        document.addEventListener('DOMContentLoaded', function() {
          FastClick.attach(document.body);
        }, false);
      }
      if(!window.Promise) {
        document.writeln('<script src="https://as.alipayobjects.com/g/component/es6-promise/3.2.2/es6-promise.min.js"'+'>'+'<'+'/'+'script>');
      }
    </script>


//main.js

/*
入口JS
 */
import Vue from 'vue'
import App from './App.vue'
import {Button} from 'mint-ui'

// 注册成标签(全局)
Vue.component(Button.name, Button)

/* eslint-disable no-new */
new Vue({
  el: '#app',
  components: {App}, // 映射组件标签
  template: '<App/>' // 指定需要渲染到页面的模板
})



//App.vue

<template>
  <mt-button type="primary" @click.native="handleClick" style="width: 100%">Test</mt-button>
</template>

<script>
  import { Toast } from 'mint-ui'
  export default {
    methods: {
      handleClick () {
        Toast('提示信息')
      }
    }
  }
</script>

<style>

</style>

Elment

  • 下载 npm i element-ui -S

实现按需打包

  • 下载 npm install babel-plugin-component -D
  • 修改 babel 配置
{
  "presets": [["es2015", { "modules": false }]],
  "plugins": [
    [
      "component",
      {
        "libraryName": "element-ui",
        "styleLibraryName": "theme-chalk"
      }
    ]
  ]
}

示例代码

//main.js

import Vue from 'vue'
import { Button, MessageBox, Message} from 'element-ui'
import App from './App.vue'

Vue.component(Button.name, Button)
Vue.component(MessageBox.name, MessageBox)
Vue.component(Message.name, Message)
Vue.prototype.$alert = MessageBox.alert
Vue.prototype.$message = Message
/* 或写为
 * Vue.use(Button)
 * Vue.use(Message)
 */

/* eslint-disable no-new */
new Vue({
  el: '#app',
  components: {App}, // 映射组件标签
  template: '<App/>' // 指定需要渲染到页面的模板
})

//App.vue

<template>
  <el-button :plain="true" @click="open">打开消息提示</el-button>
</template>

<script>
export default {
  methods: {
    open() {
      this.$alert('这是一段内容', '标题名称', {
        confirmButtonText: '确定',
        callback: action => {
          this.$message({
            type: 'info',
            message: `action: ${ action }`
          })
        }
      })
    }
  }
}
</script>


©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 219,366评论 6 508
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,521评论 3 395
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 165,689评论 0 356
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,925评论 1 295
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,942评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,727评论 1 305
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,447评论 3 420
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,349评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,820评论 1 317
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,990评论 3 337
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,127评论 1 351
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,812评论 5 346
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,471评论 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 32,017评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,142评论 1 272
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,388评论 3 373
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 45,066评论 2 355

推荐阅读更多精彩内容

  • ## 框架和库的区别?> 框架(framework):一套完整的软件设计架构和**解决方案**。> > 库(lib...
    Rui_bdad阅读 2,911评论 1 4
  • PS:转载请注明出处作者: TigerChain地址: //www.greatytc.com/p/db7...
    TigerChain阅读 64,584评论 5 81
  • 第一节 vue:读音: v-u-eview vue和angular区别?vue——简单、易学指令以 v-xxx一片...
    黑色的五叶草阅读 1,131评论 0 1
  • 响应式布局的理解 响应式开发目的是一套代码可以在多种终端运行,适应不同屏幕的大小,其原理是运用媒体查询,在不同屏幕...
    懒猫_6500阅读 789评论 0 0
  • vue-cli3项目搭建配置以及性能优化 在之前的开发中主要用的是vue-cli2,最近空闲时间比较多,接下来有新...
    bayi_lzp阅读 19,483评论 16 68