形式:元素的属性
自定义指令允许你对DOM元素进行底层操作(其实Vue作为一个框架是面向数据的,它更支持你面向数据编程)
内置指令和自定义指令,通过自己定义指令可以了解指令的实质
2. v-for: 遍历列表,对象,整数(从1开始) (是否设置key值,动态双向绑定)
3. v-cloak结合 display:none; 防止抖动
4. v-bind: 动态绑定 缩写 :
5. v-model: 一些表单元素的双向绑定
6. v-html (XSS警告)
7. v-text
8. v-once
9.** v-on 事件处理(敲黑板!划重点)** 缩写 @
10. v-pre
// 全局注册
Vue.directive(id,[definition])
// 局部注册 v-focus
new Vue({
el:"#app",
directives: {
focus: {
}
}
})
<div v-mydirective></div>
// v-mydirective为自己定义的指令
<div id="app">
<input type="text" v-focus>
</div>
<script src="../node_modules/vue/dist/vue.js"></script>
<script>
// 注册全局的自定义属性
Vue.directive(‘focus‘, {
inserted: function(el) {
// 聚焦元素
el.focus();
}
});
const app = new Vue({
el: "#app",
});
</script>
<body>
<div id="app" v-demo:foo.a.b="message">
</div>
<script src="../node_modules/vue/dist/vue.js"></script>
<script>
// 定义全局的指令
Vue.directive(‘demo‘, {
bind: function(el, binding, vnode) {
var s = JSON.stringify;
el.innerHTML =
‘1. name: ‘ + s(binding.name) + ‘<br />‘ +
‘2. value: ‘ + s(binding.value) + ‘<br />‘ +
‘3. expression: ‘ + s(binding.expression) + ‘<br />‘ +
‘4. argument: ‘ + s(binding.arg) + ‘<br />‘ +
‘5. modifiers: ‘ + s(binding.modifiers) + ‘<br />‘ +
‘6. vnode keys: ‘ + Object.keys(vnode).join(‘, ‘) + ‘<br />‘;
}
// Object.keys() 获取对象的全部属性
});
const app = new Vue({
el: "#app",
data: {
message: "Vue.js很牛逼!"
},
methods: {
}
})
</script>
</body>
如果bind和update的行为相同,且该自定义指令只需要使用这两个函数,可以简写。
<div id="app">
<p v-color-swatch="color">我就是很帅!</p>
</div>
<script src="../node_modules/vue/dist/vue.js"></script>
<script>
// 这里的function代替了bind和update钩子函数
Vue.directive(‘color-swatch‘, function(el, binding) {
console.log(el, binding);
el.style.backgroundColor = binding.value;
});
const app = new Vue({
el: "#app",
data: {
color: "red"
}
})
</script>
传给指令的值可以使任何合法的JavaScript表达式
传入对象字面量
<div id="app">
<div v-demo="{color:‘white‘,text:‘hello!‘}"></div>
</div>
<script src="../node_modules/vue/dist/vue.js"></script>
<script>
Vue.directive(‘demo‘, function(el, binding) {
const {
color,
text
} = binding.value;
console.log(color);
console.log(text);
})
const app = new Vue({
el: "#app"
})
</script>
https://github.com/suckitfa/dropdown-menu.git
- 《Vue.js从入门到实战》
- Vue官方文档
原文:https://www.cnblogs.com/rookie123/p/14757877.html