您的位置:首页 > 产品设计 > UI/UE

使用Vuejs编写单js组件

2017-12-30 20:06 399 查看

1.引用方式

我们使用Vue进行普通页面开发却不使用webpack等技术时,定义组件可以只依赖单js文件进行开发

然后像正常引用js文件那样进行引用

<scriptsrc="../Content/plugins/selectIcon/selectIcon.js"></script>


2.组件定义

组件的html内容我们可以使用script模板、字符串、ajax请求获取等方式进行加载,这里为了保持组件引用简单,我们对一段html进行压缩成一行定义为变量。

varhtml='<modalv-model="isshow"title="选择图标"@on-ok="ok"@on-cancel="cancel"><i-formstyle="height:300px;overflow-y:scroll"></i-form></modal>';
//注册
Vue.component('icon-component',{
props:['isshow'],
template:html,
mounted:function(){
var_this=this;
_this.$nextTick(function(){
$(".icons-item").on("click",function(){
$(".icons-item").removeClass("icons-itemact");
$(this).addClass("icons-itemact");
//添加标记
$("p[data-v-4ed37512]").removeAttr("data-flag");
$("p",$(this)).attr("data-flag",true);
});

$(".icons-item").on("dblclick",function(){
varicon=$("p",$(this)).text().trim();
$("#txtSelectIcon").val(icon);
_this.$emit('myevent','0');
});
});
},
methods:{
ok:function(){
varicon=$("p[data-flag]").text().trim();
$("#txtSelectIcon").val(icon);
this.$emit('myevent','0');
},
cancel:function(){this.$emit('myevent','0');}
}
})


3.父页面使用

<divid="SelectICONModal">
<keep-alive>
<icon-componentv-bind:isshow="isShow"@myevent="CloseIcon"></icon-component>
</keep-alive>
</div>


variconVueObj=newVue({
el:"#SelectICONModal",
data:{
isShow:false
},
methods:{
CloseIcon(){
this.isShow=false;
}
}
});


4.页面传值

我们页面传值使用两种方式进行传递

父页面像子页面传值使用props进行传递

<!--父页面-->
<icon-componentv-bind:isshow="isShow"...

//组件定义
Vue.component('icon-component',{
props:['isshow'],...


子页面像父页面传值使用$emit触发定义的事件

<!--父页面-->
<icon-componentv-bind:isshow="isShow"@myevent="CloseIcon"></icon-component>

//父页面初始化组件时,定义方法
methods:{
CloseIcon(){
this.isShow=false;
}
}

//组件触发
this.$emit('myevent','0');


                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: