小王的学习笔记(十八)——动态组件、混入、自定义指令、filter、render、plugin

动态组件

动态渲染一个组件<component :is='组件名'></component>,在默认情况下组件在切换时会卸载原页面,返回的时候重新创建,使用<keep-alive>,组件在第一次加载时会创建,并对当前组件进行缓存

<keep-alive>
    <component :is='组件名'></component>
</keep-alive>
混入

把组件中可复用的功能提取出来,混入中的数据会和使用组件中的数据合并,如果有重名现象,会以组件的数据为准,组件的钩子函数和混入对象的钩子函数重名时,会产生一个数组,依次执行(混入对象、根组件)

let mixin = {
	//当前的mixin是混入对象
	//混入对象拥有和组件一样的属性和方法
    data(){},
    created(){},
    methods:{}
}
new Vue({
    mixins:[mixin]
})

混入也是可以进行全局注册的。一旦使用全局混入,它就会影响每一个之后创建的 Vue 实例。但是使用恰当时,可以用来为自定义选项注入处理逻辑。

Vue.mixin({ 
	created: function () {} 
})
自定义指令

指令注册完成之后 v-指令名 使用

全局注册
Vue.directive('指令名',{
    
})
局部注册
new Vue({
    directive:{
        指令名:{

        }
    }
})
过滤器filter

过滤器是对即将显示的数据做进一步的筛选处理,然后进行显示,值得注意的是过滤器并没有改变原来的数据,只是在原数据的基础上产生新的数据。过滤器可以用在两个地方:双花括号插值和 v-bind 表达式 。过滤器应该被添加在 JavaScript 表达式的尾部,由“管道”符号指示{{ birthday | fmtDate }},可以被用于一些常见文本的格式化。

全局注册
Vue.filter('fmtDate', function(date){
	return date?moment(date).format('YYYY-MM-DD HH:mm'):'';
})
局部注册
filters: {
	fmtDate: function(date){
	  return date?moment(date).format('YYYY-MM-DD HH:mm'):'';
	}
}
渲染函数render
<div id="app">
        <anchored-heading :level="1">Hello world!</anchored-heading>
        <anchored-heading :level="2">Hello world!</anchored-heading>
        <anchored-heading :level="3">Hello world!</anchored-heading>
        <anchored-heading :level="4">Hello world!</anchored-heading>
        <anchored-heading :level="5">Hello world!</anchored-heading>
        <anchored-heading :level="6">Hello world!</anchored-heading>
    </div>
    <script>
        Vue.component('anchored-heading', { 
            // 渲染函数
            render: function (createElement) { 
            return createElement( // 该方法用于创建虚拟节点 vnode
                'h' + this.level, // 标签名称
                this.$slots.default // 子节点数组
            )}, 
            //该元素的配置信息
            props: { level: { type: Number, required: true } } 
        })
        new Vue({
            el:'#app'
        })
    </script>
plugin

插件通常用来为 Vue 添加全局功能。Vue.js 的插件暴露了一个 install 方法。这个方法的第一个参数是 Vue 构造器,第二个参数是一个可选的选项对象:

new Vue({ 
MyPlugin.install = function (Vue, options) { 
	// 1. 添加全局方法或 property 
	Vue.myGlobalMethod = function () {
	 // 逻辑... 
	 }	
	// 2. 添加全局资源
	Vue.directive('my-directive', {})	
	// 3. 注入组件选项	
	Vue.mixin({ created: function () { // 逻辑... } ... })	 
	// 4. 添加实例方法
	Vue.prototype.$myMethod = function (methodOptions) { // 逻辑... } 
}

通过在new Vue之前调用Vue.use()方法Vue.use(MyPlugin)使用组件

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值