Vue.js的自定义指令 directive

js教程评论608 views阅读模式

这次给大家带来Vue.js的自定义指令 directive,使用Vue.js的自定义指令directive的注意事项有哪些,下面就是实战案例,一起来看一下。

以自定义v-css指令为例:

局部指令

<script>
  export default {    //自定义v-css指令
    directives: {      css: {
        inserted (el, bind) {          let styleObj = bind.value          let arr = []          for (let key in styleObj) {
            arr.push(key + ':' + styleObj[key])
          }
          arr = arr.join(';')
          el.style.cssText = arr
        }
      }
    }</script>

全局指令
在main.js文件中自定义全局的指令

Vue.directive('css', {
  inserted (el, binding) {    let styleObj = binding.value    let arr = []    for (let key in styleObj) {
      arr.push(key + ':' + styleObj[key])
    }
    arr = arr.join(';')
    el.style.cssText = arr
  }
})

使用自定义指令

<p v-css="{color: 'orange', 'font-size': '24px'}">我是p标签</p>

1.png

相信看了本文案例你已经掌握了方法,更多精彩请关注php教程其它相关文章!

推荐阅读:

Vue.js的计算属性和数据监听

Vue.js的事件绑定 - 内置事件绑定、自定义事件绑定

Vue.js的列表渲染 v-for 数组 对象 子组件

以上就是Vue.js的自定义指令 directive的详细内容,更多请关注php教程其它相关文章!

企鹅博客
  • 本文由 发表于 2020年8月29日 10:57:02
  • 转载请务必保留本文链接:https://www.qieseo.com/396691.html

发表评论