今天碰到一個同學(xué)問了laydate在vue中的使用問題,因為以前在項目中也用過laydate,也算有一些了解,所以在這里做一個簡單的測試
官方網(wǎng)址:http://www.layui.com/laydate/
GitHub地址:https://github.com/sentsin/laydate/
測試文件:新建vue的webpack模板
1、首先是組件里import引用
這里是在components中的hello.vue中進行
<input type="text" id="test" v-model="date" class="ipt" @click="getDate" >
import laydate from 'layui-laydate'
export default {
name: 'hello',
data () {
return {
date: null
}
},
methods: {
getDate () {
console.log(0)
laydate.render({
elem: '#test',
done: (value) => {
this.date = value
}
})
}
}
}
效果:沒有報錯,點擊輸入框也沒有反應(yīng)

2、在 組件中單獨引入不行,那么我們來嘗試一下在入口文件index.html中做常規(guī)js文件引用,并在index.html中調(diào)用
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<script src="static/laydate/laydate.js"></script>
<title>laydatedemo</title>
<style>
.box{width: 200px; margin:0 auto }
</style>
</head>
<body>
<div id="app" ></div>
<!-- built files will be auto injected -->
<div class="box">
<input type="text" id="test" >
</div>
<script>
laydate.render({
elem: '#test',
done: (value) => {
this.date = value
}
})
</script>
</body>
</html>
效果:沒有報錯,laydate能夠正常使用

3、上面的第二種方式laydate是能夠使用的,但是一般來說項目需求會要求我們是在組件之中調(diào)用laydate,而不是在入口文件中調(diào)用,那么第三種方法,我們在index.html中引入,而在組件中調(diào)用
index.html
<script src="static/laydate/laydate.js"></script>
hello.vue
<template>
<div class="hello">
<H1>laydate時間插件測試</H1>
<input type="text" id="test" v-model="date" class="ipt" >
</div>
</template>
<script>
export default {
name: 'hello',
mounted() {
laydate.render({
elem: '#test',
done: (value) => {
this.date = value
}
})
}
}
</script>
結(jié)果:運行報錯,提示laydate沒有聲明

4、我們在入口文件引入了laydate.js,并且在入口文件中引用是可行的,但是在組件中引用卻會報未聲明的錯誤,會不會是我們在入口文件引入的laydate是全局的,但是在組建中沒有加載到,所以第四次測試時獲取全局的laydate對象,依然是在index.html引入js文件,然后在組件中調(diào)用
index.html
<script src="static/laydate/laydate.js"></script>
hello.vue
<template>
<div class="hello">
<H1>laydate時間插件測試</H1>
<input type="text" id="test" v-model="date" class="ipt">
</div>
</template>
<script>
export default {
name: 'hello',
data () {
return {
date: null,
//獲取全局的laydate,帶入到組件中
laydate: window.laydate
}
},
mounted() {
this.laydate.render({
elem: '#test',
done: (value) => {
this.date = value
}
})
}
}
</script>
效果:沒有報錯,點擊能夠正常調(diào)用laydate

這個測試到這里應(yīng)該算是結(jié)束了,但是既然這個插件能夠在mounted中調(diào)用,那么能不能在methods的方法中調(diào)用呢
附加測試:在4的基礎(chǔ)上進行修改,測試laydate能否在methods中運行
index.html
<script src="static/laydate/laydate.js"></script>
hello.vue
<template>
<div class="hello">
<H1>laydate時間插件測試</H1>
<input type="text" id="test" v-model="date" class="ipt" @click="setDate">
</div>
</template>
<script>
export default {
name: 'hello',
data () {
return {
date: null,
//獲取全局的laydate,帶入到組件中
laydate: window.laydate
}
},
methods: {
setDate() {
this.laydate.render({
elem: '#test',
done: (value) => {
this.date = value
}
})
}
}
}
</script>
效果:沒有報錯,點擊第一次,沒有反應(yīng),失去焦點之后再重新點擊,時間框出現(xiàn),laydate插件調(diào)用成功
對于這個bug,暫時沒有什么頭緒,如果有大神們知道是怎么回事,歡迎給我留言
注:轉(zhuǎn)載請注明出處