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

之前一篇博客寫了怎麼讓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 啓動







發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章