Vue实现带参数的自定义指令示例

正文

自定义指令参考官方文档:vuejs.bootcss.com/guide/custo…

<!DOCTYPE html>
<html >
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>自定义指令带参数</title>
  </head>
  <body>
    <div >
      <input type="text" v-color="msg" />
    </div>
    <script src="vue.js"></script>
    <script>
      //自定义指令-带参数
      Vue.directive("color", {
        bind: function (el, binding) {
          el.style.backgroundColor = binding.value.color;
        },
      });
      const vm = new Vue({
        el: "#app",
        data: {
          msg: {
            color: "blue",
          },
        },
      });
    </script>
  </body>
</html>

通过上面的代码,可以看到定义了一个color的指令,在使用的时候传递了msg对象。

所以这个对象会给binding这个参数,我们通过这个参数的value 属性获取msg对象中的color属性的值,然后用来设置文本框的背景色。

这里使用了bind这个钩子函数:只调用一次,第一次绑定指令到元素时调用,我们可以在此绑定只执行一次的初始化动作。

以上就是Vue实现带参数的自定义指令示例详解的详细内容,更多关于Vue 带参数自定义指令的资料请关注其它相关文章!

原文地址:https://juejin.cn/post/7186930719946932285