最近入坑vue 做一点小的记录 有不对的 辛苦指出 会第一时间更改上新
1.组件的创建
一般一个可以复用的模块 会被开发为一个组件
目录结构一般为
每一个组件的所有内容会被放在一个单独的文件夹的,包括引入的js,css,图片等 这样更便利于协作开发项目
组件的引入
例子:App.vue文件 引入组件来讲
1.模块化开发 webpack+vue-cli构建项目
下面两种写法都是可以的
import changNum from './components/changeNum/changeNum' import changNum from './components/changeNum/changeNum.vue'
声明组件
components:{ changNum },
html中 直接以标签形式添加
<changNum/>
2. 非模块化开发
在同一个html页面中
<script src="http://static.yuntongauto.com/js/vue.min.js"></script> <script src="http://static.yuntongauto.com/js/[email protected]"></script>
先声明组件
Vue.component('successtips', { data: function () { return { count: 0 } }, props:{ msg:{ require:true } }, methods:{ closeA:function (event) { this.$emit('parent-close') } }, template: '<div class="pop">\n' + '<div class="tips" ><i></i><div v-html="msg"></div><div class="close" v-on:click="closeA"></div></div>\n' + '</div>' })
html中 运用组件 (双标签 单标签皆可)
<successtips v-if="successtips" @parent-close="tipsclose" v-bind:msg="msg"></successtips>
再new Vue实例
new Vue({ el:'#app', data:{ successtips:false, msg:'<span>您已成功领取优惠券</span><br/>请耐心等待客服联系~' }, methods:{ closeA:function (event) { this.getmsg=false; }, tipsclose:function () { this.successtips=false; }, getMsgFn:function (event) { this.getmsg=true; console.log(this.getmsg) }, isConnect:function (data, fn) { if(Number(data.code)==0){ if(fn){ fn() } }else{ this.tipsFn('<span>'+data.message+'</span>') } }, tipsFn:function (txt) { if(!txt) { txt = '<span>服务器走丢了</span><br/>请联系客服处理~' } this.msg=txt; this.successtips=true; } }, mounted:function () { var that=this; if(base.GeTUrlParam().b){ this.$http.jsonp(base.path+"一个接口地址",{ params:{ brandId:base.GeTUrlParam().b } }).then(function (res) { //成功函数 var data=res.body; this.isConnect(data,function () { if(data.result.serviceNetworkList.length && data.result.couponList.length){ }else{ that.tipsFn('<span>信息获取失败</span><br/>产品券或者4s店未录入,请检查信息完整心') } }) },function (reason) { //失败函数 this.tipsFn() }); }else{ that.tipsFn('<span>品牌id未获取到</span><br/>请检查链接完整性') } } })
2.父组件和子组件的通信
父组件的data通过 v-bind:msg="msg"的方法 传递给子组件
<tips v-if='isTips' v-bind:msg="msg" />
子组件中 通过props接受 用法和子组件自己的data一样 直接 this.msg就可以找到
export default { name: "tips", props:{ msg:{type:String} } }
子组件改变 从而使得父元素中 data发生改变 这样改如何处理?
vue不支持 子组件改变父组件的数据 但是 可以通过调用父组件的方法 并传递相应的数据 从而达到 子组件改变父组件数据的目的
子组件调用父组件的方法 从而做到改变父组件的data
父组件 中有一个可以改变数据的方法
export default { name: 'App', data:function () { return{ money:1000,msg:'这个是提示语',isTips:false } }, components:{ tips }, methods:{ changeMsg:function (txt) { this.msg=txt; } } }
子组件 @parent-tipsfn="tipsFn"
<tips v-if='isTips' v-bind:msg="msg" @changeMsg="changeMsg" />
在子组件中使用触发子组件方法 进而促发父组件方法
methods:{ reduce:function () { if(this.num>0){ this.num--; }else{ this.$emit('changeMsg', '数量已达最小') } }, plus:function () { if((this.num*this.money)<10000){ this.num++; }else{ this.$emit('changeMsg', '单笔支付不得超过10000元') } } }
目前先记录这么多 以后接着补充