vue 引入自定义js 并使用

JavaScript07

vue 引入自定义js 并使用,第1张

1.首先创建一个js

ex: test.js 

const referrerPhone = [

  { pattern: /^1[3456789]\d{9}$/, message: '手机号格式不正确', trigger: 'blur' }

]

export default {

referrerPhone 

}

import validators  from '../路径/test.js'

定义成对象方便调用

Vue.prototype.$validators  = validators 

this.$validators.referrerPhone 

=======================================================================================================

第二种 不是公用

1.创建一个 js

// 弹框提示

function tips(this_, message_, type_){

  this_.$message({

    message: message_,

    type: type_

  })

export { //很关键

  tips,

}

import { tips} from '../xx.js'

tips(this, '非法操作,不能删除admin用户!', 'error')

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的最后加入

1234567

plugins: [ new webpack.optimize.CommonsChunkPlugin('common.js'), new webpack.ProvidePlugin({ jQuery: "jquery", $: "jquery" })]

(4) 在main.js 引入就ok了(测试这一步不用也可以)

1

import $ from 'jquery'

(5)然后 npm run dev 就可以在页面中直接用$ 了.

在vue中导入自定义的css文件或js文件

css文件

在main.js中导入公共的css

import '../static/css/common.css' //引入公用css

在页面中引入单独css

<style scoped>

@import '../../static/css/header.css'

</style>

Js文件

自定义js 中写:

function title(t){

alert(t)

}

export {

title //多个方法在此处json中export出去

}

页面中使用:

<template>

<div>

<button class="btn" @click="clickme">click me</button>

</div>

</template>

<script>

import {title} from './js/common.js' //可以选择需要的方法引入

export default {

data(){

return{

}

},

methods:{

clickme(){

title('你点我了')

}

}

}

</script>

或者

import Comjs from './js/common.js' //引入公用js

Vue.prototype.$comjs = Comjs//添加到vue属性中

自定义js 中写:

const comjs = {

}

comjs.title = function (title) {

alert(title)

}

export default comjs

页面中使用:

<template>

<div>

<button class="btn" @click="clickme">click me</button>

</div>

</template>

<script>

export default {

data(){

return{

}

},

methods:{

clickme(){

this.$comjs.title('你点我了')

}

}

}

</script>