vue2引入外部js文件(以hammer.js为例)

来源:互联网 发布:淘宝ppr外丝活接 编辑:程序博客网 时间:2024/06/03 17:36

之前一篇博客写了怎么让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'//引入外部jsimport './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 启动