1. 程式人生 > >vue2引入外部js檔案(以hammer.js為例)

vue2引入外部js檔案(以hammer.js為例)

但是怎麼把外部的這個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 啟動