【问题标题】:Custom directive自定义指令
【发布时间】:2020-06-09 02:39:34
【问题描述】:

documentation for custom directives 演示了同时使用动态参数和值:

指令参数可以是动态的。例如,在v-mydirective:[argument]="value" 中,参数可以根据我们组件实例中的数据属性进行更新!这使得我们的自定义指令可以灵活地在整个应用程序中使用。

如果"value" 不包含空格,则可以正常工作。但是在值中添加一个空格(例如v-mydirective:[argument]="some value")会导致 Nuxt 阻塞:

invalid expression: Unexpected identifier in

    some value

  Raw expression: v-mydirective:[argument]="some value"

什么是问题,我该如何解决它,以便我可以使用带有空格的字符串作为自定义指令的值?

【问题讨论】:

    标签: vue.js nuxt.js vue-directives


    【解决方案1】:

    问题:

    发生这种情况是因为当我们传递带有空格的value 时,vuejs 会评估表达式并尝试找到具有属性somevaluedata 选项。但是由于这些属性名称都不存在,因此我们得到了提到的错误。

    一个简单的例子来解释这一点,我们将value 传递为:

    v-mydirective:[argument]="2"
    

    如果我们在 bind 函数中执行 console.log

    console.log(binding.value)
    

    您将看到输出显示为2。但是,如果我们将value 传递为:

    v-mydirective:[argument]="2 + 2"
    

    如果我们在bind 函数中执行console.log,有趣的是这次显示的输出是4 而不是2 + 2


    解决方案:

    对此有两种可能的解决方案:

    解决方案 #1:

    您可以简单地将some value 用单引号括起来,然后将其作为字符串传递,例如:

    v-mydirective:[argument]="'some value'"
    

    这样表达式将直接作为字符串计算。

    演示:

    Vue.directive('pin', {
      bind: function (el, binding, vnode) {
        console.log(binding.value)
      }
    })
    
    new Vue({
      el: '#dynamicexample',
      data: function () {
        return {
          direction: 'left',
        }
      }
    })
    #dynamicexample {
      font-family: "Source Sans Pro", "Helvetica Neue", Arial, sans-serif;
      color: #304455;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.min.js"></script>
    <div id="dynamicexample">
      <p v-pin:[direction]="'some value'">I am pinned onto the page at 200px to the left.</p>
    </div>

    解决方案 #2:

    您还可以为它创建一个单独的data 选项,例如:

    data: function () {
      return {
        myValue: 'some value'
      }
    }
    

    然后你可以在如下指令中使用它:

    v-mydirective:[argument]="myValue"
    

    演示:

    Vue.directive('pin', {
      bind: function (el, binding, vnode) {
        console.log(binding.value)
      }
    })
    
    new Vue({
      el: '#dynamicexample',
      data: function () {
        return {
          direction: 'left',
          myValue: 'some value'
        }
      }
    })
    #dynamicexample {
      font-family: "Source Sans Pro", "Helvetica Neue", Arial, sans-serif;
      color: #304455;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.min.js"></script>
    <div id="dynamicexample">
      <p v-pin:[direction]="myValue">I am pinned onto the page at 200px to the left.</p>
    </div>

    【讨论】:

      猜你喜欢
      • 2023-04-04
      • 2019-11-06
      • 2015-11-16
      • 2014-06-24
      • 2018-10-20
      • 1970-01-01
      • 1970-01-01
      • 2012-12-14
      • 1970-01-01
      相关资源
      最近更新 更多