常用内置指令:
- v:text : 更新元素的 textContent
- v-html : 更新元素的 innerHTML
- v-if : 如果为 true, 当前标签才会输出到页面
- v-else: 如果为 false, 当前标签才会输出到页面
- v-show : 通过控制 display 样式来控制显示/隐藏
- v-for : 遍历数组/对象
- v-on : 绑定事件监听, 一般简写为@
- v-bind : 强制绑定解析表达式, 可以省略 v-bind
- v-model : 双向数据绑定
- ref : 指定唯一标识, vue 对象通过$els 属性访问这个元素对象
- v-cloak : 防止闪现, 与 css 配合: [v-cloak] { display: none }
自定义指令: - 注册全局指令
Vue.directive('my-directive', function(el, binding){
el.innerHTML = binding.value.toUpperCase()
}) - 注册局部指令
directives : {
'my-directive' : {
bind (el, binding) {
el.innerHTML = binding.value.toupperCase()
}
}
} - 使用指令
v-my-directive='xxx'
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
</style>
</head>
<body>
<div id="demo">
<p v-upper-text="msg1"></p>
<p v-lower-text="msg1"></p>
</div>
<div id="demo2">
<p v-upper-text="msg2"></p>
<p v-lower-text="msg2"></p>
</div>
</body>
<script src="../js/vue.js"></script>
<script>
//el:指令属性所在的标签对象
//binding:包含指令相关信息数据的对象
Vue.directive('upper-text', function(el, binding) {
el.innerHTML = binding.value.toUpperCase();
})
new Vue({
el:"#demo",
data:{
msg1:'NBA I LOVE THIS GAME!'
},
directives:{
'lower-text'(el,binding) { //注册局部指令,只在当前vm管理范围内有效
el.textContent= binding.value.toLowerCase();
}
}
})
new Vue({
el:"#demo2",
data:{
msg2:'Just Do it!'
}
})
</script>
</html>