例如淘宝一页下来各个商品,每个商品都可以看成是一个模板,每个产品之间传递了不同的参数(价格,图片,文字描述),这样的模板就是组件。
和过滤器类似,有的组件需要在不同页面中出现
Vue.component('product', { template: '<div class="product" >模板</div>' })传递参数给组件
<product name="模板1"></product> <product name="模板2"></product> Vue.component('product', { props:['name'], template: '<div class="product" >{{name}}</div>' })组件内的参数和组件外的值关联(比如input输入的数据传递到组件内)
组件外的值:<input v-model="outName" ><br> //双向绑定 <product v-bind:name="outName"></product> <script> Vue.component('product', { props:['name'], template: '<div class="product" >{{name}}</div>' }) new Vue({ el: '#div1', data:{ outName:'产品名称' } }) </script>和在Vue对象上增加methods类似
<script> //在模板上绑定点击的methods Vue.component('product', { props:['name','sale'], template: '<div class="product" v-on:click="increaseSale">{{name}} 销量: {{sale}} </div>', methods:{ increaseSale:function(){ this.sale++ } } }) </script>template 部分因为比较复杂,就不好写在一个 单引号 ’ ’ 里维护起来,所以就直接写在html里,然后通过html dom 获取出来,这样编写起来略微容易一点。
<div id="tempalate"> ****** </div> <script> var tempalateDiv=document.getElementById("tempalate").innerHTML; var templateObject = { props: ['product'], template: tempalateDiv, methods: { ******* } } Vue.component('product', templateObject); </script>vue.js 里的路由相当于就是局部刷新。
(需要额外的库:vue-router.min.js)
1.定义路由组件,就是定义template
2.定义路由,为路由赋值这些路由组件
3.实例路由,就是用到VueRouter包
4.挂载路由,就是用到Vue包
<div class="menu"> <!-- router-link相当于就是 href--> <router-link to="/user">用户管理</router-link> <router-link to="/product">产品管理</router-link> <router-link to="/order">订单管理</router-link> </div> <div style="float: right"> <!--点击上面的/user,那么/user对应的内容就会显示在router-view这里--> <router-view></router-view> </div> <script> var User={template:'<div>用户管理页面的内容</div>'} var Product={template: '<div>产品管理页面的内容</div>'} var Review={template:'<div>订单管理页面的内容</div>'} var routes=[ {path:'/user',component:User}, {path:'/product',component: Product}, {path:'/review',component:Review} ] //创建VueRouter实例 var router = new VueRouter({ routes:routes }); //绑定路由 new Vue({ el:"#app", router }) </script>当然还可以传参(传个json对象啥的)
<div v-xart="{color:'red',text:'best learning video'}"> 好好学习,天天向上 </div> <script> Vue.directive('xart', function (el,canshu) { el.innerHTML = el.innerHTML + '( ' + canshu.value.text + ' )' el.style.color = canshu.value.color }) </script>使用vue框架,需要在合适的时机做合适的事情(和生命周期挂钩)
vue生命周期经历的阶段:开始创建、初始化数据、编译模板、挂载Dom、渲染→更新→渲染、销毁等一系列过程
1.实例化vue对象2.初始化事件和生命周期3.beforeCreate函数(此时没有真实的DOM)4.挂载数据(属性和computed运算)5.created函数(Vue对象有数据,但是没有DOM)6.检查(el属性和template属性)7.beforeMount函数8.模板编译(vue对象的数据替换模板内容)9.monuted函数,数据挂载完毕 Vue对象加载成功(这个时候发送异步请求)10.beforeUpdate(组件更新前11.update(组件更新后12.销毁(销毁前还有组件激活函数)目前还不是很能理解什么是钩子函数,大概是在对应的生命周期绑定函数吧,之后可以回来再看看
Vue一般不用原生的Ajax而是使用比较流行的ajax框架—fetch,axios
vue-cli,vue crud 要用node.js方面以及webpack等的知识
具体的运用在后面的学习了这部分前端知识再进行补充