vue参数传递方法

  1. 全局事件总线
  • main.js
new Vue({
  render: h => h(App),  //解析模板
  beforeCreate(){
    Vue.prototype.$bus = this  //安装全局事件总线,vue原型对象添加$bus对象指向vm
  }
}).$mount('#app')
//组件实例对象的原型对象指向vue原型对象
//VueComponent.prototype.__pro__===Vue.prototype
  • $bus绑定自定义事件
methods:{
     changname(id,name){
         this.listMsg.map(item=>{
             if(item.id === id){item.name = name}
         })
     }
}
 mounted(){
     this.$bus.$on('add',item=>{this.listMsg.unshift(item)})
     this.$bus.$on('changeMname',this.changname)//changMname为自定义事件
 },
  • 触发事件
 suremsg(item,id,msg){
   item.iswrite=false
   this.$bus.$emit('changeMname',id,msg)
 }
 //不是同一个文件
 methods:{
  addmsg(){
    const newmsg={
      name:this.msg,
      real:true,
      id:Math.random()
    }
    this.$bus.$emit('add',newmsg)
  }
}
  1. v-bind(传递数据或方法)
<list-body :listMsg='listMsg' ref="listbody"/>//listMisg是data数据
<list-foot :listMsg='listMsg' :clear='clear'/>//clear为事件
//
 clear(){
     this.listMsg=this.listMsg.filter(item=>!item.real)
 },

  • 接收
 props:['listMsg','clear'],
 //此处chanearall方法可以传参
 methods:{
   clearall(){
     this.clear()
   }
 }
  1. pubsub订阅与发布
  • 安装引入
npm install pubsub-js 
//
import pubsub from "pubsub-js";
  • 使用
mounted() {
  // this.sendtot2()
  pubsub.subscribe("pubmessage", (subid, data) => {
    this.message = data;
  });
},//订阅
methods:{
  //   react(){
  //       this.$bus.$emit('brotherMessage',this.message)
  //   }
    react(){
        pubsub.publish('pubmessage',this.message)
    }
}//发布
  1. 自定义事件(子给父传值)
父级
<list-foot @myevenet='sendmsg' ref='x'/>
methods:{sendmsg(e){}}
or
mounted(){this.$refs.$on('myevenet',e=>{})}
----------
子级list-foot
this.$emit('myevenet',e)

你可能感兴趣的:(vue-study,vue)