之前一篇博客写了怎么让vue用hammer封装触摸事件

但是怎么把外部的这个hammer.js文件融入vue-cil中呢?

下面是步骤

基本命令:

vue init webpack hxammerdemo

cd hxammerdemo/

cnpm install


新建红框内的js目录和 hammer.js文件(这个文件就是hammer.min.js内容复制进去的) 和 touchvue.js文件


编辑touchvue.js:

import Vue from 'vue'
//引入外部js
import './hammer.js'


function vueTouch(el,type,binding){
	this.el = el;
	this.type = type;
	this.binding = binding;
	//直接调用
	var hammertime = new Hammer(this.el);
	hammertime.on(this.type,this.binding.value);
};

//包装成指令
const tap = Vue.directive("tap",{
    bind:function(el,binding){
        new vueTouch(el,"tap",binding);
    }
});

const swipeleft = Vue.directive("swipeleft",{
    bind:function(el,binding){
        new vueTouch(el,"swipeleft",binding);
    }
});

const swiperight = Vue.directive("swiperight",{
    bind:function(el,binding){
        new vueTouch(el,"swiperight",binding);
    }
});

const press = Vue.directive("press",{
    bind:function(el,binding){
        new vueTouch(el,"press",binding);
    }
});

//导出需要的指令
export{tap,swipeleft,swiperight,press}


然后在main.js中直接引入

// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import router from './router'
//引入
import {tap,swipeleft,swiperight,press} from './assets/js/touchvue.js'

Vue.config.productionTip = false

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

修改src/components/HelloWorld.vue

<template>
  <div class="hello">
    <h1>{{ msg }}</h1>
    <h2 
	    v-tap="tap"
	    v-swipeleft = "swipeleft"  
	    v-swiperight = "swiperight"  
	    v-press = "press" 
    >
    		Essential Links
    </h2>
    
  </div>
</template>

<script>
export default {
  name: 'HelloWorld',
  data () {
    return {
      msg: 'Welcome to Your Vue.js App'
    }
  },
  methods:{
  	tap(s,e){
  		console.log("触摸点击");
  	},
  	swipeleft(s,e){  
        console.log("向左滑动:x偏移量["+s.deltaX+"],y偏移量["+s.deltaY+"]");  
    },  
    swiperight(s,e){  
        console.log("向右滑动:x偏移量["+s.deltaX+"],y偏移量["+s.deltaY+"]");  
    },  
    press(s,e){  
        console.log("长按")  
    },  
  }
}
</script>

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

一切就绪以后用 cnpm run dev 启动







Logo

前往低代码交流专区

更多推荐