vue中常用的缩写
vue中常用的缩写绑定数据 v-bind监听事件 v-on
·
vue中常用的缩写
绑定数据 v-bind
v-bind
的缩写是 :
可以使用 setAttribute 设置 , getAttribute 获取的属性都可以使用这种动态绑定
列举一些使用频率比较高的,比如:
:title
、:class
、:style
、:key
、:item
、:index
、:src
、:href
例子:
// HTML
<div v-bind:title="message">绑定数据</div>
<div :title="message">绑定数据</div>
//上面两种写法都能渲染成下面这样
<div title="现在的时间 --》 2020-10-29 19:25:38">绑定数据</div>
// JS
data() {
return {
message: '现在的时间--》' + this.formatTime(new Date()),
};
},
methods: {
fillZero(n) {
return n < 10 ? '0' + n : n;
},
formatTime(time) {
var year = time.getFullYear(),
month = time.getMonth() + 1,
date = time.getDate(),
hours = time.getHours(),
minutes = time.getMinutes(),
seconds = time.getSeconds();
var Hours = this.fillZero(hours);
var Minutes = this.fillZero(minutes);
var Seconds = this.fillZero(seconds);
return (
[year, month, date].join('-') +
' ' +
[Hours, Minutes, Seconds].join(':')
);
},
},
监听事件 v-on
v-on
的缩写是 @
常用的有@click
点击事件、@change
域的内容发生改变时触发的事件、@mouseenter
鼠标移入事件、@mouseleave
鼠标移出事件、@mousemove
鼠标移动事件、@mousedown
鼠标按下事件、@mouseup
鼠标松开事件、@input
输入文本时触发的事件、@focus
获取焦点事件、@blur
失去焦点事件等等
例子:
// HTML
<div v-on:click="showLocation">点击展示地点</div>
<div @click="showLocation">点击展示地点</div>
<div class="geo"></div>
// JS
methods: {
showLocation(){
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(this.showPosition, this.showError);
} else {
document.querySelector('.geo').innerHTML = "此浏览器不支持地理位置(Geolocation is not supported by this browser.)";
}
},
showPosition(position) {
document.querySelector('.geo').innerHTML = "Latitude: " + position.coords.latitude + " & Longitude: " + position.coords.longitude;
},
showError(error) {
switch (error.code) {
case error.PERMISSION_DENIED: // 用户不允许地理定位
document.querySelector('.geo').innerHTML = "用户拒绝了地理定位请求(User denied the request for Geolocation.)"
break;
case error.POSITION_UNAVAILABLE: // 无法获取当前位置
document.querySelector('.geo').innerHTML = "位置信息不可用(Location information is unavailable.)"
break;
case error.TIMEOUT: // 操作超时
document.querySelector('.geo').innerHTML = "获取用户位置的请求超时(The request to get user location timed out.)"
break;
case error.UNKNOWN_ERROR: // 未知错误
document.querySelector('.geo').innerHTML = "发生未知错误(An unknown error occurred.)"
break;
}
}
},
更多推荐
已为社区贡献2条内容
所有评论(0)