2017-10-04 51 views
0

我试图定义一个动态文字指令,根据插件内的Vue DOCVue.js动态Litera Directivel的插件,不绑定正确

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

App.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) 
    }) 
}) 

回答

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'