0

根据插件内的 Vue 文档,我正在尝试定义一个 Dynamic Literal Directive

myPlugin.js

    const defaultNoiseColor = 'white'

    ...

    const MyPlugin = {
      install (Vue, options) {
        console.log('installing MyPlugin')
        Vue.directive('noise', {
          isDynamicLiteral: true,
          bind (el, binding, vnode) {
            const noisecolor = binding.expression || defaultNoiseColor
            console.log('NOISE BIND: ', noisecolor)
          },
          update (el, binding, vnode) {
            const noisecolor = binding.expression || defaultNoiseColor
            console.log('NOISE UPDATE', noisecolor)
          },
          unbind (el, binding, vnode) {
            console.log('NOISE UNBIND: ')
          }
        })
        ...
      }
    }

    export default MyPlugin

在我的 main.js 中,我添加了

main.js

...
Vue.use(MyPlugin)
...

我的 App.vue 中有自定义指令(带小胡子)

应用程序.vue

    <template>
      <div id="app" class="container"  v-noise="'{{ noisecolor }}'">
        ...
      </div>
    </template>

    <script>
    ...
    window.data = {
      kittens: true,
      noisecolor: 'brown'
    }

    export default {
      ...
      data () {
        return window.data
      }
    }
    </script>

所以noisecolor应该是'棕色',但是在测试myPlugin时,我在绑定期间得到默认的白色......(根据文档应该在更新期间?)

myPlugin.spec.js

import Vue from 'vue'
import App from '@/App'
import MyPlugin from '@/plugins/MyPlugin'

import { mount } from 'avoriaz'

Vue.use(MyPlugin)
...

describe('MyPlugin', () => {
  let wrapper

  beforeEach(() => {
    wrapper = mount(App, { attachToDocument: true, propsData: { noisecolor: 'brown' } })
  })

  it('should run', () => {
    Vue.noise.start()
    ...
    expect(true).to.equal(true)
  })
})
4

1 回答 1

0

发现问题:应该使用 binding.value 而不是 binding.expression

解决了添加

    console.log('NOISE BINDING: ', binding)
    const noisecolor = binding.value || defaultNoiseColor

这导致以下控制台输出:

LOG LOG: 'NOISE BINDING: ', Object{name: 'noise', rawName: 'v-noise',
value: 'brown', expression: 'noisecolor', modifiers: Object{}, def:
Object{isDynamicLiteral: true, bind: function bind(el, binding, vnode)
{ ... }, update: function update(el, binding, vnode) { ... }, unbind:
function unbind(el, binding, vnode) { ... }}}

LOG LOG: 'NOISE BIND: ', 'brown'
于 2017-10-04T07:05:53.507 回答