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

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

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

xiaoxiaok   2023-02-03 我要评论

正文

自定义指令参考官方文档: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 id="app">
      <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这个钩子函数:只调用一次,第一次绑定指令到元素时调用,我们可以在此绑定只执行一次的初始化动作。

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们