vue监听器,过滤器与插槽的概念

56 阅读1分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 10 月更文挑战」的第29天,点击查看活动详情

侦听器

数据变化时执行异步或开销比较大的操作

watch: {

firstName: function(val) {

this.fullName = val + ' ' + this.lastName;

},

lastName: function(val) {

this.fullName = this.firstName + ' ' + val;

},

}

 

自定义过滤器

//首字母大写

{{msg | upper | lower}}

Vue.filter('upper', function (val) {

return val.charAt[0].toUpperCase() + val.slice(1);

})

Vue.filter('lower', function (val) {

return val.charAt[0].toLowerCase() + val.slice(1);

})

测试数据

 

//局部过滤器

filters: {

upper: function (val) {

return val.charAt[0].toUpperCase() + val.slice(1);

}

}

 

//带参数的过滤器

<div>{{date | format('yyyy-MM-dd')}}</div>

 

Vue.filter(format, function (value, arg) {

if(arg == 'yyyy-MM-dd') {

ret += value.getFullYear() + '-' + (value.getMonth() + 1) + '-' + value.getDate();

return ret;

}

return value;

})

 

data() {

return {

date: new Date();

}

}

 

Vue.set的使用,当数据不渲染时

Vue.set(vm.list, 2 , 'lemon');

vm.$set(vm.list, 1, 'lemon);

vm.$set(vm.info, 'gender', 'female');

 

vue调试工具 Devtools

1.克隆仓库

2.安装依赖包

3.构建

4.打开chrome扩展页面

5.选中开发者模式

6.加载已解压的扩展,选择shells/chrome

非父子组件间传值

1.单独的事件中心管理组件间的通信

 

父组件

<div>

<button @click=handle"">销毁事件</button>

</div>

 

//提供事件中心

var hub = new Vue();

 

methods: {

handle: function() {

//触发兄弟组件的事件

hub.$emit('tom-event', 1):

}

}

mounted: function() {

//监听事件

hub.$on('jerry-event', (val) =>{

thiis.num +=val;

})

}

 

methods: {

handle: function() {

//触发兄弟组件的事件

hub.$emit('jetrry-event', 2):

}

}

mounted: function() {

//监听事件

hub.$on('tom-event', (val) =>{

thiis.num +=val;

})

}

 

//父组件销毁事件

methods: {

handle: function () {

hub.$off('tom-event');

hub.$off('jerry-event);

}

}

 

组件插槽-匿名插槽


<alert-box>弹窗</alert-box>

 

Vue.component('alert-box', {

template: `

<div>

<strong>ERROR:</strong>

<slot>默认内容</slot>

</div>

`

})

 

具名插槽 中的"name"属性绑定元素

    <base-layout>

<!-- 1-->

<p slot="header">标题信息</slot>

<!-- 2-->

<template slot="header">

<p>标题信息1</p>

<p>标题信息2</p>

</template>

</base-layout>

 

<header>

<slot name="header"></slot>

</header>

 

作用域插槽

父组件对子组件进行加工处理

既可以复用子组的slot, 又可以使slot内容不一致

<fruit-list :list='list'>

<template slot-scope="slotProps">

<strong v-if=slotProps.info.id =="3" class="current">

{{slotProps.info.name}}

</strong>

<span v-else>{{slotProps.info.name}}</span>

</template>

</fruit-list>

 


<div>

<li :key="item.id" v-for="item in list">

<slot :Info='item'>{{item.name}}</slot>

</li>

</div>