结果 res -c 允许 message cti 属性。 只读 改变
指令 (Directives) 是带有
前缀的特殊属性。 它可以写在DOM元素上,对html进行操作。常用的指令比如有:
- v-
- v-if,
- v-else,
- v-show,
等。这些都是官方直接给定的,另外vue也允许注册自定义指令,有时这很有用。
- v-for
自定义一个指令很简单,官网给出一个简单的例子,自定义一个聚焦指令
- v-focus:
- // 注册一个全局自定义指令 `v-focus`
- Vue.directive(‘focus‘, {
- // 当被绑定的元素插入到 DOM 中时……
- inserted: function(el) {
- // 聚焦元素
- el.focus()
- }
- })
上面几行代码就全局注册了一个指令并可以执行,当给一个输入框加上这个指令时,页面加载就会使该框获得焦点。
- <input v-focus>
说明:
‘focus‘:如你所见,是指令的名称,不带
前缀;
- v-
inserted:这是一个钩子函数,表示被绑定元素插入父节点时调用,指令定义函数提供了多个钩子函数,下面再介绍。
另外,你也可以局部注册指令,组件中也接受一个 directives 的选项:
- directives: {
- focus: {
- // 指令的定义
- inserted: function(el) {
- el.focus()
- }
- }
- }
指令定义函数提供了几个钩子函数(可选)
:只调用一次,指令第一次绑定到元素时调用。
- bind
:被绑定元素插入父节点时调用。
- inserted
:所在组件的VNode更新时调用,但是可能发生在其子 VNode 更新之前。
- update
:指令所在组件的 VNode 及其子 VNode 全部更新后调用。
- componentUpdated
:只调用一次,指令与元素解绑时调用。
- unbind
他们中每一个都有相同的三个参数:el,binding和vnode,在update和componentUpdated中,还会有参数oldVnode,以区分传递的旧值和新值。
:指令所绑定的元素,可以用来直接操作 DOM 。
- el
:一个对象,包含以下属性:name,value,oldValue,expression,arg和modifiers。
- binding
:Vue 编译生成的虚拟节点。
- vnode
:上一个虚拟节点,仅在 update 和 componentUpdated 钩子中可用。
- oldVnode
注意:除了 el 之外,其它参数都应该是只读的。
其中,你注意到binding参数中有多个属性,要搞清楚他们分别代表了什么,这很重要。
- <div id="app">
- <p v-demo:foo.a.b="message"></p>
- </div>
- Vue.directive(‘demo‘, {
- bind(el, binding, vnode) {
- //给绑定的元素添加内容
- el.innerHTML = `name: $ {
- binding.name
- }; < br > value: $ {
- binding.value
- }; < br > expression: $ {
- binding.expression
- }; < br > argument: $ {
- binding.arg
- }; < br > modifiers: $ {
- JSON.stringify(binding.modifiers)
- };`
- }
- });
- new Vue({
- el: ‘#app‘,
- data: {
- message: "hello"
- }
- });
结果:
- name:demo; //指令名,不包括 v- 前缀
- value:hello; //指令的绑定值
- expression:message; //字符串形式的指令表达式
- argument:foo; //传给指令的参数,可选。
- modifiers:{"a":true,"b":true}; //一个包含修饰符的对象。
还有一个oldValue是指令绑定的前一个值,仅在 update 和 componentUpdated 钩子中可用。无论值是否改变都可用。
到这里,你可能有点糊涂了,东西看起来有点多,其实并不是,你只是不熟悉。这些官网介绍的很清楚,你需要的是一个更具体的例子。
现在来创建一个自定义指令,比如我想创建一个可以操作定位的指令,就叫他
。
- v-position
- Vue.directive(‘position‘, {
- bind(el, binding, vnode) {
- el.style.position = ‘fixed‘;
- el.style.top = binding.value + ‘px‘;
- }
- });
- <div id="app">
- <p v-position=‘100‘>我距离顶部100px</p>
- </div>
现在v-position只能控制到顶部的距离,我们还可以自由控制方向:
- <p v-position:left=‘50‘>我距离左侧50px</p>
- Vue.directive(‘position‘, {
- bind(el, binding, vnode) {
- el.style.position = ‘fixed‘;
- let d = (binding.arg == ‘top‘ ? ‘top‘: ‘left‘);
- el.style[d] = binding.value + ‘px‘;
- }
- });
另外,你还可以控制多个值:
- <p v-position="{top:‘100‘,left:‘50‘}">我距离左侧50px,距离顶部100px</p>
- Vue.directive(‘position‘, {
- bind(el, binding, vnode) {
- el.style.position = ‘fixed‘;
- el.style.top = binding.value.top + ‘px‘;
- el.style.left = binding.value.left + ‘px‘;
- }
- });
这就是vue自定义指令的一些简单应用,你可以创建出更高级灵活的自定义指令。
vue自定义指令
结果 res -c 允许 message cti 属性。 只读 改变
原文:http://www.cnblogs.com/wjaaron/p/7878670.html
来源: http://www.bubuko.com/infodetail-2403961.html