vue3.0自定义指令-vue自定义指令实现

lxf2023-05-06 01:08:01
摘要

这篇文章主要为大家介绍了Vue实现带参数的自定义指令示例详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪

正文

自定义指令参考官方文档Vuejs.bootCSS.com/guide/custo…

<!DOCTYPE html>
<html lang="en">
  <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 keylink">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 带参数自定义指令的资料请关注编程网其它相关文章!