Vue 学习笔记三、触摸事件、轮播图

190 阅读2分钟

  • 页面跳转

如果存在 标签,且跟它同级有其他标签需要使用

再次包装,否则会报错,例如下面:

<template>
     <div>
         <div>home view</div>
         <router-link to='/list'>列表页</router-link>
     </div>
</template>

  • mate初始化


安装好之后在运行

npm run start

然后可以到 package.json 文件中就能看到 dependencies 选项中包含了 fastclick

"dependencies": {
    "fastclick": "^1.0.6",
    "vue": "^2.5.2",
    "vue-router": "^3.0.1"
},

然后在 main.js 中使用如下

import Vue from 'vue'
import App from './App'
import router from './router'
import fastClick from 'fastclick'
import './assets/styles/reset.css'
import './assets/styles/border.css'

Vue.config.productionTip = false
fastClick.attach(document.body)

/* eslint-disable no-new */
new Vue({
  el: '#app',
  router: router,
  components: { App: App },
  template: '<App/>'
})

  • 文件别名添加 别名添加流程

添加好别名之后,就可以直接使用 styles 作为文件开头使用。注意,修改完成别名之后使用会报错,那是因为需要重启服务器。所以你可以重新

npm run start

另外在 main.js 文件里面导入文件只需要

import './assets/styles/iconfont.css'

或者

import '@/assets/styles/iconfont.css'

因为 @ 在文件别名里面代表的就是 src 文件夹。

但是在 .vue 文件中的 标签里使用的时候则需要这样用

import '~@/assets/styles/iconfont.css'

需要在开头加上 ~ 符号。

补充一下别名的使用结果,用上面两个文件的导入举例为:

main.js:

import 'styles/iconfont.css'

.vue 中的 使用:

import '~styles/iconfont.css'


  • Chrome 插件 vue devtools 方便 Vue 调试

  • 安装 axios

如果需要模拟本地数据需要把本地数据 .json 文件放在 static 文件目录下,如果放在 src 文件夹下 打开链接时会自动定位到首页,导致无法加载,所以只能放在 static 文件夹下。

  npm install axios --save

axios请求本地数据样式


  • 请求转移

请求转移示例

图中就将 /static/mock 转成 /api ,只要请求调用 /api/xxx, 就相当于是调用 /static/mock 下的文件,示例:

methods: {
   getHomeInfo () {
    // axios.get('/static/mock/index.json').then(res => {
    axios.get('/api/index.json').then(res => {
      console.log(res)
    }).catch(err => {
      console.error(err)
    })
   }
 },
mounted () {
  this.getHomeInfo()
}

传参1:

axios.get('/api/index.json?id=' + this.$route.params.id).then(res => {
   console.log(res)
}).catch(err => {
   console.error(err)
})

传参2:

axios.get('/api/index.json', {
   params: {
     id: this.$route.params.id
   }
}).then(res => {
   console.log(res)
}).catch(err => {
   console.error(err)
})

  • 滚动效果

better-scrolliscroll 的封装,使用更加友好。

npm install better-scroll --save

解决better-scroll导致点击事件失效的原因和解决方法:

mounted () {
   const options = {
     click: true,
     tap: true
   }

   this.scroll = new Bscroll(this.$refs.wrapper, options)
}

  • 触摸事件

    @touchstart='handleTouchStart' 触摸开始 @touchmove='handleTouchMove' 触摸中 @touchend='handleTouchEnd' 触摸结束

当在触摸的时候可能会下面的滚动视图也跟着滚动那么需要这么修饰

@touchstart.prevent='handleTouchStart' 触摸开始
@touchmove='handleTouchMove' 触摸中
@touchend='handleTouchEnd' 触摸结束