# 简单的组件传值
# 组件的自定义事件
- 自定义事件可以做简单的组件传值
适用于:子组件 ===> 父组件 - 使用:子组件想给父组件传数据,那么就要在父组件中给子组件绑定自定义事件(事件的回调在父中)
- 绑定自定义事件
a. 第一种方式,在父组件中<Demo @事件名="方法"/>
b. 第二种方式,在父组件中this.$refs.demo.$on('事件名',方法) - 子组件触发自定义事件
this.$emit('事件名',数据) - 解绑自定义事件
this.$off('事件名') - 组件上也可以绑定原生DOM事件,需要使用native修饰符
@click.native="show"上面绑定自定义事件,即使绑定的是原生事件也会被认为是自定义的,需要加native,加了后就将此事件给组件的根元素
父组件
<template>
<div class="app">
<h1>{{ msg }}:{{ studentName }}</h1>
<!-- 通过父组件给子组件传递函数类型的props实现子给父传递数据 -->
<School :getSchoolName="getSchoolName"/>
<!-- 通过父组件给子组件绑定一个自定义事件实现子给父传递数据(第一种写法,使用@或v-on) -->
<!-- <Student @atguigu="getStudentName" @demo="m1"/> -->
<!-- 通过父组件给子组件绑定一个自定义事件实现子给父传递数据(第二种写法,使用ref) -->
<Student ref="student" @click.native="show"/>
</div>
</template>
mounted() {
this.$refs.student.$on('atguigu',this.getStudentName)
// 绑定自定义事件
// this.$refs.student.$once('atguigu',this.getStudentName) // 绑定自定义事件(一次性)
},
methods: {
getSchoolName(name){
console.log('App收到了学校名:',name)
},
},
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
子组件
sendStudentlName(){
// 触发Student组件实例身上的atguigu事件
this.$emit('atguigu',this.name,param1,param2)
// this.$emit('demo')
// this.$emit('click')
},
1
2
3
4
5
6
2
3
4
5
6
# WebStorage(js存储)
存储内容大小一般支持 5MB 左右(不同浏览器不一样) 浏览器端通过Window.sessionStorage和Window.localStorage属性来实现本地存储机制 相关API
- xxxStorage.setItem('key', 'value')该方法接受一个键和值作为参数,会把键值对添加到存储中,如果键名存在,则更新其对应的值
- xxxStorage.getItem('key')该方法接受一个键名作为参数,返回键名对应的值
- xxxStorage.removeItem('key')该方法接受一个键名作为参数,并把该键名从存储中删除
- xxxStorage.clear()该方法会清空存储中的所有数据 备注
- SessionStorage存储的内容会随着浏览器窗口关闭而消失
- LocalStorage存储的内容,需要手动清除才会消失
- xxxStorage.getItem(xxx)如果 xxx 对应的 value 获取不到,那么getItem()的返回值是null。JSON.parse(null)的结果依然是null
<h2>localStorage</h2>
<button onclick="saveDate()">点我保存数据</button><br/>
<button onclick="readDate()">点我读数据</button><br/>
<button onclick="deleteDate()">点我删除数据</button><br/>
<button onclick="deleteAllDate()">点我清空数据</button><br/>
<script>
let person = {name:"JOJO",age:20}
function saveDate(){
localStorage.setItem('msg','localStorage')
localStorage.setItem('person',JSON.stringify(person))
}
function readDate(){
console.log(localStorage.getItem('msg'))
const person = localStorage.getItem('person')
console.log(JSON.parse(person))
}
function deleteDate(){
localStorage.removeItem('msg')
localStorage.removeItem('person')
}
function deleteAllDate(){
localStorage.clear()
}
</script>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26