Vue06 全局事件总线 TodoList-事件总线 消息订阅与发布 TodoList-pubsub TodoList-编辑$nextTick 动画效果 github案例

全局事件总线

(没有新的api)利用自定义事件,实现兄弟组件之间的通信。

复习VueComponet

 复习重要的内置关系

 所以,在Vue的原型对象上添加属性。

 需要有$on(绑定事件,触发事件时的回调)、$emit(触发事件)。

$on、$emit、$off都在Vue的原型对象上。vm和vc都能看见。

利用beforeCreate钩子: 此时数据还没解析,数据代理、监测没开始。

main.js:

/*
const Demo = Vue.extend({});//Demo:一个Vuecomponent构造函数
const d = new Demo();//new调用,生成vc实例
Vue.prototype.x = d;//x是一个vc实例*/



//创建vue实例对象
new Vue({
  
  //将App组件放入容器中
  render: h => h(App),
  beforeCreate() {
    //安装全局事件总线
    Vue.prototype.$bus = this;//$bus是一个vm实例,$bus是它的名字,$bus在Vue原型对象上,vc能够看见,没有必要new一个vc
  },


}).$mount('#app')

 school.vue


<template>
  <div class="school">
    <h2>schoolname:{
  { name }}</h2>
    <h2>schoolage{
  { schoolage }}</h2>
    
  </div>
</template>


<script>


export default {
  name: "SchoolInfo",
  
  data() {
    return {
      name: "atguigu",
      schoolage: 20,
      stuname:'???'
    };
  },
  methods:{
    
  },
  mounted(){
    //console.log('school',this.$bus);
    //给$bus绑定hello事件、事件回调在school上
    this.$bus.$on('hello',(data)=>{
      //写成箭头函数,使this是当前组件
      this.stuname = data;
    });
  },
  beforeDestroy() {
    //销毁$bus上的hello事件
    this.$bus.$off('hello')
  },
 
};
</script>


student.vue

<template>
  <div class="student">
    <h1>{
  { msg }}</h1>
    <h2>stuname:{
  { name }}</h2>
    <h2>stuage:{
  { stuage }}</h2>
    <button @click='sendStudentName'>把学生名给school组件</button>
  </div>
</template>


<script>

export default {
  name: "StudentInfo",
  data() {
    return {
      msg: "尚硅谷666", 
      name: "jack",
      stuage: 18,
    };
  },
  methods: {
    sendStudentName(){
      //触发$bus的hello事件
      this.$bus.$emit('hello',this.stuname);
    }
  },

 
};
</script>



TodoList事件总线

让app能够直接和item通信。之前是把app上的函数一直传递下去,item接收,触发函数。

现在app收数据,item传id。给app绑定事件,事件回调。item传入id触发事件。

此时勾选、删除,触发事件的是$bus,vm

App.vue

mounted() {
    this.$bus.$on('checkTodo',this.checkTodo)
    this.$bus.$on('deleteTodo',this.deleteTodo)
  },
  beforeDestroy() {
    this.$bus.$off('checkTodo');
    this.$bus.$off('deleteTodo');
  },

item.vue


<template>
  
     <li>
      <label>
        <input type="checkbox" :checked="todo.done" @change='handleCheck(todo.id)'/>
        <!--eslint-disable-next-line vue/no-mutating-props-->
        <!--<input type="checkbox" v-model="
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值