zoukankan      html  css  js  c++  java
  • vue组件传值、通信

    vue组件传值、通信

    父组件--------》子组件
    属性
    // parent
    <HelloWorld msg="Welcome to Your Vue.js App"/>
    
    // child
    props: { msg: String }
    引用refs
    // parent
    <HelloWorld ref="hw"/>
    
    修改子组件的值
    this.$refs.hw.xx = 'xxx'
    子组件chidren
    // parent 
    this.$children[0].xx = 'xxx'
    子组件---->父组件
    自定义事件
    // parent
    <Cart @add="cartAdd($event)"></Cart>
    
    // Cart.vue 
    this.$emit('add', good)
    兄弟组件
    通过共同的父辈
    // brother1 
    	this.$parent.$on('foo', handle)
    // brother2 
    	this.$parent.$emit('foo')
    祖先和后代之间
    // ancestor 
    provide() {
     return {foo: 'foo'}
    }
    // descendant 
    inject: ['foo']

    任意两个组件之间:事件总线或vuex

    // Bus:事件派发、监听和回调管理class Bus{
    constructor(){
    // {
    //	eventName1:[fn1,fn2],
    //	eventName2:[fn3,fn4],
    // } this.callbacks = {}
    }
    $on(name, fn){
        this.callbacks[name] = this.callbacks[name] || [] 	  this.callbacks[name].push(fn)
    }
    $emit(name, args){ if(this.callbacks[name]){
        this.callbacks[name].forEach(cb => cb(args))
    }
    }
    }
    
    // main.js
    Vue.prototype.$bus = new Bus()
    
    // child1 this.$bus.$on('foo', handle)
    // child2 this.$bus.$emit('foo')
  • 相关阅读:
    图片滚动
    DOM 练习
    HTML 求阶乘之和
    JavaScript 累加求和练习 函数
    JavaScript 累加求和练习
    JavaScript
    汽车之家官网首页排版与布局
    网页搜索页面排版布局
    转---Python——numpy random类
    转---redshift database ---学习
  • 原文地址:https://www.cnblogs.com/cupid10/p/15617600.html
Copyright © 2011-2022 走看看