在Vue项目中引入其他js或库(例如jquery)

2,201 阅读1分钟

直接在main.js文件中通过import引入即可全局使用,例如:

方式一:
import $ form './lib/jquery-1.10.2.min';
说明:
1、这里jquery是放在lib目录下的。
2、使用import时刻省略.js后缀。
3、使用jquery直接操作dom元素,需要将要执行的逻辑放在methods中的方法中,同时在生命周期函数mounted函数中进行绑定,这样才能正常执行。
4、需要注意的是,在使用mounted时需和created的写法有所区别,(这里针对es5)。
5、使用mounted时建议内部使用this.$nextTick进行事件挂载,这样可以保证所有事件在DOM树渲染完成后再进行绑定,确保了事件的可执行性。
方式二:
1、先使用npm i jquery --save安装jquery
2、修改配置文件:webpack.base.conf.js,在module.exports中加入
externals: {
    jquery: 'window.$'
}
3、在需要的组件中通过以下方式引入。
var $ = require('jquery')

这里列出例子:

方法一:
<button class="btn">点击</button>
export default {
  name: "homeIndex",
  mounted:function(){
    this.$nextTick(function(){
        this.tip();
    })
  },
  data(){
      return {
          msg:"this is my first vue.app"
      }
  },
  methods: {
    tip:function(){
        $(".btn").click(function(){
           alert("你点我了"); 
        });
    }
  }
}
方法二:
webpack.base.conf.js
externals: {
    jquery: 'window.$'
}
组件页面,例如:App.vue
<template>
    <div>
        <button @click="clickTo">安妮</button>
    </div>
</template>

<script>
    var $ = require('jquery')
    export default{
        data(){
            return{
                
            }
        },
        methods:{
            clickTo(){
                console.log($(this));
            }
        }
    }
</script>