vue开发技巧2
8.功能组件是无状态的,不能被实例化。没有内部生命周期函数。一切都通过上下文参数传递。上下文属性有:1.props:提供所有prop对象2.children:VNode子节点的数组3.slots:返回包含所有槽的对象的函数4.scopedSlots:(2.6.0+)暴露的对象传入的作用域插槽。还将普通插槽公开为函数。5.data:传递给组件的整个数据对象,作为createElement的第二个参数传入组件6.parent:父组件的引用7.listeners:(2.3.0+)一个包含所有父组件作为当前组件注册事件监听器的一个对象。这是data.on的别名。8.injections:(2.3.0+)如果使用了inject选项,对象包含应该被注入的属性{{item}}
components和Vue.component本地注册exportdefault{components:{home}}全局注册Vue.component('home',home)Vue.extend有时需要挂载一些元素到On元素,需要使用extend//创建构造函数varProfile=Vue.extend({template:'
{{extendData}}实例传入的数据为:{{propsExtend}}
',//模板对应的label最外层必须只有一个labeldata:function(){return{extendData:'Thisistheextendeddata',}},props:['propsExtend']})//创建构造函数可以挂载在元素上,也可以通过组件注册或者Vue.component()//挂载在元素上。可以通过propsData.newProfile({propsData:{propsExtend:'我是实例传入的数据'}}).$mount('#app-extend')//通过组件或者Vue注册Vue。component().component('Profile',Profile)11.mixins的部分组件有重复的js逻辑校验可以放入mixinsconstmixin={created(){this.dealTime()},methods:{dealTime(){console.log('这是mixin的dealTime中的方法');}}}exportdefault{mixins:[mixin]}extends一次只能扩展一个组件constextend={created(){this.dealTime()},methods:{dealTime(){console.log('Thisismixin的dealTime中的方法');}}}exportdefault{extends:extend}Vue.use()会触发安装函数install第一个参数是Vue的构造函数,第二个参数是一个可选的options对象varMyPlugin={}MyPlugin.install=function(Vue,options){//添加全局资源Vue.directive('click',{bind(el,binding,vnode,oldVnode){//准备绑定,添加时间监听console.log('命令的绑定my-directivehasbeenexecuted');},inserted:function(el){//获取绑定元素console.log('my-directive插入的指令被执行')},update:function(){//初始化会调用一次,更新也会调用useconsole.log('执行my-directive的更新命令');},componentUpdated:function(){console.log('执行my-directive的componentUpdated命令');},unbind:function(){//做清理工作//例如事件监听器console.log('命令my-directive的unbind被执行');}})//混入组件Vue.mixin({created:function(){console.log('createdoftheinjectedcomponentiscalled');console.log('options的值为',options)}})Vue.prototype.$myMethod=function(methodOptions){console.log('调用实例方法myMethodCalled');}}Vue.use(MyPlugin,{someOption:true})Vue.nextTick页面加载完成后需要获取焦点,dom更新完成后立即调用事件mounted(){//因为mounted阶段dom没有渲染完成,所以需要$nextTickthis.$nextTick(()=>{this.$refs.inputs.focus()//通过$refs获取dom并绑定焦点方法})}Vue.directive,for例如,将颜色转换为指令你可以使用//全局定义Vue.directive("change-color",function(el,binding,vnode){el.style["color"]=binding.value;})//使用
{{message}} 1.bind只调用一次,当指令第一次绑定到元素时,这个钩子可以用来定义一个初始化绑定动作时执行一次2.inserted:绑定元素插入父节点时调用(如果父节点存在即可调用,文档中不需要存在)3.update:绑定元素所在模板时调用被更新,并且不管绑定值是否存在变化,通过比较更新前后的绑定值,忽略不必要的模板更新4.componentUpdate:当绑定元素所在的模板完成一个更新更新周期时调用17.Vue.filter将时间戳转换成年月日的公共方法//使用//在双花括号中{{message|capitalize}}//in`v-bind`