03.vue-ajax、vue UI 组件库

2019-06-09  本文已影响0人  leofight

vue-ajax

vue 项目中常用的 2 个 ajax 库

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

实现按需打包

"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

实现按需打包

{
  "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>


上一篇下一篇

猜你喜欢

热点阅读