vue引用js文件的多种方式(推荐)
1、vue-cli webpack全局引入jquery
(1) 首先 npm install jquery --save (--save 的意思是将模块安装到项目目录下,并在package文件的dependencies节点写入依赖。)
(2)在webpack.base.conf.js里加入
1 var webpack = require("webpack")
(3)在module.exports的最后加入
1 plugins: [
2 new webpack.optimize.commonschunkplugin('common.js'),
3 new webpack.provideplugin({
4 jquery: "jquery",
5 $: "jquery"
6 })
7 ]
(4) 在main.js 引入就ok了 (测试这一步不用也可以)
1 import $ from 'jquery'
(5)然后 npm run dev 就可以在页面中直接用$ 了.
2、vue组件引用外部js的方法
项目结构如图:
content组件代码:
01 <template>
02 <div>
03 <input ref='test' id="test">
04 <button @click='diyfun'>click</button>
05 </div>
06 </template>
07 <script>
08 import {myfun} from '../js/test.js' //注意路径
09 export default {
10 data () {
11 return {
12 testvalue: ''
13 }
14 },
15 methods:{
16 diyfun:function(){
17 myfun();
18 }
19 }
20 }
21 </script>
test.js代码:
1 function myfun() {
2 console.log('success')
3 }
4 export { //很关键
5 myfun
6 }
用到了es6的语法。
3、单vue页面引用内部js方法
(1) 首先 npm install jquery --save (--save 的意思是将模块安装到项目目录下,并在package文件的dependencies节点写入依赖。)
(2) 在需要引用的vue页面import引入$,然后使用即可
这个图中有黄色的警告,如果把console.log($)改成这样:
1 export default{
2 mounted: function(){
3 console.log($)
4 }
5 }
就不会有了,原因可能是得符合vue中js的写法吧