Vue基础-webStorage/组件自定义事件/全局事件总线/消息订阅与发布

浏览器本地存储(webStorage)

localStorage
存储,注意前key后value,两个都是字符串,对象可以存储为JSON字符串

localStorage.setItem('msg', 'hello')

let person = {'name':'张三','age':18}
localStorage.setItem('person',JSON.stringify(person))

查看浏览器本地存储:
F12--->Application(应用)---> Local Storage(本地存储空间)--->选择对应网址--->就能看到存储的key和value了

读取

localStorage.setItem('person',JSON.stringify(person))

当读取不到数据的时候,返回null,转成对象依然是null

删除

localStorage.removeItem('person')

清空

localStorage.removeItem('person')

sesionStorage
sesionStorage所有API与localStorage一模一样,区别是:sesionStorage浏览器关闭后就清空了,而localStorage浏览器关闭不会清空。

注意用户主动清除浏览器缓存都会清空。

组件自定义事件

绑定($emit)
用法:

//父vue v-on:可以简写为@
<ChildVue v-on:send="receive"/>
<ChildVue v-on:send.once="receive"/>//只触发一次

methods: {
    receive(value) {
        this.age = value
    }
},
//子vue
methods: {
   sendName(){
       this.$emit('send',this.age)
   }
},

还可以使用ref绑定

 <Teacher ref="teacher" />

mounted() {
   //可以直接获取子类属性
    console.log(this.$refs.teacher.age)
   //绑定自定义事件,点击按钮时触发
    this.$refs.teacher.$on('send',this.receive)
    //只触发一次
    this.$refs.teacher.$once('send', this.receive)
}

解绑

unbind() {
    this.$off('send')
    //解绑多个事件
    this.$off(['send','more'])
    //解绑所有事件
    this.$off()
}

组件上也可以绑定原生DOM事件,需要使用 native 修饰符。

<!-- 不使用 .native:点击无效,因为组件需要由 $emit('click') 触发-->
<BaseButton @click="handleClick">没有 native 的点击</BaseButton>

<!-- 使用 .native:点击有效,监听器被加到根元素 <button> 上 -->
<BaseButton @click.native="handleClick">有 native 的点击</BaseButton>

全局事件总线

是一种组件间通信方向,可以实现任意组件间通信。
1、安装全局事件总线,main.js文件中Vue添加$bus属性

new Vue({
  render: h => h(App),
  beforeCreate(){
    Vue.prototype.$bus = this
  }
}).$mount('#app')

2、传递数据组件中

<button @click="sendBrother">传递给兄弟</button>

methods: {
  //点击按钮传递数据
  sendBrother() {
    this.$bus.$emit('sendB', '97')
  },
  unbind(){
    //解绑
    this.$bus.$off('sendB')
  }
},
beforeDestroy(){
  this.unbind()
}

3、接收数据组件中

methods: {
    //打印接收到的数据
    receiveB(value){
        console.log(value)
    },
},
mounted(){
    this.$bus.$on('sendB', this.receiveB)
},

消息订阅与发布

js无法实现,需要借助第三方库:
pubsub
1、安装第三方库

yarn add pubsub-js

2、消息发布

import PubSub from 'pubsub-js'

 PubSub.publish('hello',25)

3、消息订阅和接收

//引入
import PubSub from 'pubsub-js'
//挂载时订阅
mounted() {
     this.pubId = PubSub.subscribe('hello',this.receive)
},
//接收消息
receive(msgName,data) {
    if (msgName == 'hello') {
         this.age = data
     }
}
//取消订阅
beforeCreate(){
     PubSub.unsubscribe(this.pubId)
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容