javascript - 怎样写这个指令,让它看起来像是一个整体?
巴扎黑
巴扎黑 2017-04-11 11:54:24
[JavaScript讨论组]

  • {{email}}

Vue.directive('DirEmail',{
    bind:function(){},
    update:function(newValue){
        if(!newValue) return;
        var needAt=this.modifiers.needat || false,
            emails=[],
            at=newValue.indexOf('@'),
            user='';
        if(needAt && !~at){
            this.vm.emails=emails;
            return false;
        }
        if(~at){
            this.vm.host=newValue.substr(at);
            user=newValue.substr(0,at);
        }
        else{
            this.vm.host='';
            user=newValue;
        }
        for(var n in hosts){
            emails.push(user+'@'+hosts[n]);
        }
        this.vm.emails=emails;
    },
    unbind:function(){}
})

var hosts=['126.com','163.com','qq.com','yahoo.com','yahoo.com.cn'];
new Vue({
    el:"#EmailInput",
    data:function(){
        return {
            emailAddress:'',
            host:'',
            emails:[]
        }
    }
})

现在指令跟实例是分开的,但是逻辑上,它们应该是一个整体才对,应该怎么写才能把它们两个整合到一起呢?是把指令里边的东西,写在实例里边还是怎么样呢?

我把实例中的data移动到directive里边,刷新没问题,往里一打值就报错。我在bind钩子上使用this.vm.$set也是报错,都报

Vue warn: You are setting a non-existent path "emailAddress" on a vm instance. Consider pre-initializing the property with the "data" option for more reliable reactivity and better performance.

好像是说无法在实例上设置不存在的数据。


我找到方法了,是在directive的bind中使用Vue.set(),把属性设置进去。但是为什么不能用this.vm.$set,教程里边明明写着可以用这两种方法,但是使用后者总报上边那个错(设置不存在的路径错误)。

巴扎黑
巴扎黑

全部回复(1)
阿神

實際上如果你要建立一個 全局 的指令的話,就只能這樣做,可以放在實例裡面,但就不是全局了,而是當前實例底下才有作用,例如你放在 Component 底下,那就只有該 Component 底下才能用。

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号