浏览器本地存储

WebStorage(js 本地存储)

  1. 存储内容大小一般支持 5MB 左右(不同浏览器可能还不一样)
  2. 浏览器端通过Window.sessionStorage和Window.localStorage属性来实现本地存储机制 相关API
  3. xxxStorage.setItem('key', 'value')该方法接受一个键和值作为参数,会把键值对添加到存储中,如果键名存在,则更新其对应的值
  4. xxxStorage.getItem('key')该方法接受一个键名作为参数,返回键名对应的值
  5. xxxStorage.removeItem('key')该方法接受一个键名作为参数,并把该键名从存储中删除
  6. xxxStorage.clear()该方法会清空存储中的所有数据
  7. 备注
    • SessionStorage存储的内容会随着浏览器窗口关闭而消失
    • LocalStorage存储的内容,需要手动清除才会消失
    • xxxStorage.getItem(xxx)如果 xxx 对应的 value 获取不到,那么getItem()的返回值是null
    • JSON.parse(null)的结果依然是null

localstorage

<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>

sessionstorage

<h2>sessionStorage</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(){
    sessionStorage.setItem('msg','sessionStorage')
    sessionStorage.setItem('person',JSON.stringify(person))
  }
  function readDate(){
    console.log(sessionStorage.getItem('msg'))
    const person = sessionStorage.getItem('person')
    console.log(JSON.parse(person))
  }
  function deleteDate(){
    sessionStorage.removeItem('msg')
    sessionStorage.removeItem('person')
  }
  function deleteAllDate(){
    sessionStorage.clear()
  }
</script>

组件自定义事件

  1. 一种组件间通信的方式,适用于:子组件 ===> 父组件

  2. 使用场景:子组件想给父组件传数据,那么就要在父组件中给子组件绑定自定义事件(事件的回调在A中)

  3. 绑定自定义事件 a 第一种方式,在父组件中<Demo @事件名="方法"/>或<Demo v-on:事件名="方法"/> b 第二种方式,在父组件中this.$refs.demo.$on('事件名',方法)

    <Demo ref="demo"/>
    ......
    mounted(){
       this.$refs.demo.$on('atguigu',this.test)
    }
    
  4. 触发自定义事件this.$emit('事件名',数据)

  5. 解绑自定义事件this.$off('事件名')

  6. 组件上也可以绑定原生DOM事件,需要使用native修饰符 @click.native="show"上面绑定自定义事件,即使绑定的是原生事件也会被认为是自定义的,需要加native,加了后就将此事件给组件的根元素

  7. 注意:通过this.$refs.xxx.$on('事件名',回调函数)绑定自定义事件时,回调函数要么配置在methods中,要么用箭头函数,否则 this 指向会出问题

App.vue

<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"/> <!-- 🔴native -->
  </div>
</template>

<script>
  import Student from './components/Student'
  import School from './components/School'

  export default {
    name:'App',
    components:{School,Student},
    data() {
      return {
        msg:'你好啊!',
        studentName:''
      }
    },
    methods: {
      getSchoolName(name){
        console.log('App收到了学校名:',name)
      },
      getStudentName(name,...params){
        console.log('App收到了学生名:',name,params)
        this.studentName = name
      },
      m1(){
        console.log('demo事件被触发了!')
      },
      show(){
        alert(123)
      }
    },
    mounted() {
      this.$refs.student.$on('atguigu',this.getStudentName) // 🔴绑定自定义事件
      // this.$refs.student.$once('atguigu',this.getStudentName) // 绑定自定义事件(一次性)
    },
  }
</script>

<style scoped>.app{background-color: gray;padding: 5px;}</style>

Student.vue

<template>
	<div class="student">
		<h2>学生姓名:{{name}}</h2>
		<h2>学生性别:{{sex}}</h2>
		<h2>当前求和为:{{number}}</h2>
		<button @click="add">点我number++</button>
		<button @click="sendStudentlName">把学生名给App</button>
		<button @click="unbind">解绑atguigu事件</button>
		<button @click="death">销毁当前Student组件的实例(vc)</button>
	</div>
</template>

<script>
	export default {
		name:'Student',
		data() {
			return {
				name:'张三',
				sex:'男',
				number:0
			}
		},
		methods: {
			add(){
				console.log('add回调被调用了')
				this.number++
			},
			sendStudentlName(){
				// 触发Student组件实例身上的atguigu事件
				this.$emit('atguigu',this.name,666,888,900)
				// this.$emit('demo')
				// this.$emit('click')
			},
			unbind(){
        // 🔴解绑
				this.$off('atguigu') //解绑一个自定义事件
				// this.$off(['atguigu','demo']) //解绑多个自定义事件
				// this.$off() //解绑所有的自定义事件
			},
			death(){
        // 销毁了当前Student组件的实例,销毁后所有Student实例的自定义事件全都不奏效
				this.$destroy()
			}
		},
	}
</script>

<style lang="less" scoped>
	.student{background-color: pink;padding: 5px;margin-top: 30px;}
</style>

全局事件总线

一种可以在任意组件间通信的方式,本质上就是一个对象,它必须满足以下条件:

  1. 所有的组件对象都必须能看见他
  2. 这个对象必须能够使用$on$emit$off方法去绑定、触发和解绑事件

使用步骤

  1. 定义全局事件总线

    new Vue({
       	...
       	beforeCreate() {
       		Vue.prototype.$bus = this // 安装全局事件总线,$bus 就是当前应用的 vm
       	},
        ...
    })
    
  2. 使用事件总线

    a接收数据:A组件想接收数据,则在A组件中给$bus绑定自定义事件,事件的回调留在A组件自身

    b提供数据:this.$bus.$emit('xxx',data)

    export default {
        methods(){
            demo(data){...}
        }
        ...
        mounted() {
            this.$bus.$on('xxx',this.demo)
        }
    }
    
  3. 最好在beforeDestroy钩子中,用$off()去解绑当前组件所用到的事件

main.js

import Vue from 'vue'
import App from './App.vue'

Vue.config.productionTip = false

new Vue({
  el:'#app',
  render: h => h(App),
  beforeCreate() {
    Vue.prototype.$bus = this // 安装全局事件总线
  }
})

App.vue

<template>
	<div class="app">
		<School/>
		<Student/>
	</div>
</template>

<script>
	import Student from './components/Student'
	import School from './components/School'

	export default {
		name:'App',
		components:{ School, Student }
	}
</script>

<style scoped>.app{background-color: gray;padding: 5px;}</style>

School.vue

<template>
  <div class="school">
    <h2>学校名称:{{ name }}</h2>
    <h2>学校地址:{{ address }}</h2>
  </div>
</template>

<script>
  export default {
    name: "School",
    data() {
      return {
        name: "尚硅谷",
        address: "北京",
      };
    },
    mounted() {  //🔴
      // console.log('School',this)
      this.$bus.$on("hello", (data) => {
        console.log("我是School组件,收到了数据", data);
      });
    },
    beforeDestroy() {  //🔴
      this.$bus.$off("hello");
    },
  };
</script>

<style scoped>.school {background-color: skyblue;padding: 5px;}</style>

Student.vue

<template>
  <div class="student">
    <h2>学生姓名:{{ name }}</h2>
    <h2>学生性别:{{ sex }}</h2>
    <button @click="sendStudentName">把学生名给School组件</button> //🔴
  </div>
</template>

<script>
  export default {
    name:'Student',
    data() {
      return {
        name:'张三',
        sex:'男'
      }
    },
    methods: {  //🔴
      sendStudentName(){
        this.$bus.$emit('demo', this.name)
      }
    }
  }
</script>

<style scoped>.student{background-color: pink;padding: 5px;margin-top: 30px;}</style>