# 动态指令参数
小常识:

指令的参数可以是动态的。例如,在 `v-mydirective:[argument]="value"` 中,argument 参数可以根据组件实例数据进行更新!这使得自定义指令可以在应用中被灵活使用。 例如你想要创建一个自定义指令,用来通过固定布局将元素固定在页面上。我们可以像这样创建一个通过指令值来更新竖直位置像素值的自定义指令: ```javascript

Scroll down the page

Stick me 200px from the top of the page

Vue.directive('pin', { bind: function (el, binding, vnode) { el.style.position = 'fixed' el.style.top = binding.value + 'px' } }) new Vue({ el: '#baseexample' }) ``` 这会把该元素固定在距离页面顶部 200 像素的位置。但如果场景是我们需要把元素固定在左侧而不是顶部又该怎么办呢?这时使用动态参数就可以非常方便地根据每个组件实例来进行更新。 ```javascript

Scroll down inside this section ↓

I am pinned onto the page at 200px to the left.

Vue.directive('pin', { bind: function (el, binding, vnode) { el.style.position = 'fixed' var s = (binding.arg == 'left' ? 'left' : 'top') el.style[s] = binding.value + 'px' } }) new Vue({ el: '#dynamicexample', data: function () { return { direction: 'left' } } }) ``` 结果:
![在这里插入图片描述](https://img-blog.csdnimg.cn/10de551b6d6140baa679a077f06f59bb.gif)
这样这个自定义指令现在的灵活性就足以支持一些不同的用例了。
**函数简写**
在很多时候,你可能想在 bind 和 update 时触发相同行为,而不关心其它的钩子。比如这样写:
```javascript Vue.directive('color-swatch', function (el, binding) { el.style.backgroundColor = binding.value }) ```
小测试:
根据上方小常识完成填空:动态指令参数 `(__1__)`,`(__2__)`可以根据组件实例数据进行更新!

## 答案 1、v-mydirective:[argument]="value";2、argument 参数 ## 选项 ### A 1、v-mydirective:[argument]="value";2、ele参数 ### B 1、v-mydirective:[value]="argument";2、argument 参数 ### C 1、v-mydirective:[value]="argument";2、ele参数