vue组件传值大全_父传子_子传父_非父子

父传子

第一种方法

 通过自定义属性

//父组件
<template>
  <div id="app">
    <HelloWorld msg='你好di'></HelloWorld>
  </div>
</template>

//子组件
<template>
  <div>
    {{msg}}
  </div>
</template>
<script>
export default {
  name:"HelloWorld",
  props:['msg']
}

第二种方法通过$refs

this.$refs.hw相当于helloworld组件的实例,我们可以修改实例上的data属性,就像vm.data='xxx'

//父组件
<template>
  <div id="app">
    <HelloWorld  ref="hw"></HelloWorld>
  </div>
</template>
 mounted(){
    this.$refs.hw.a='di'
  }

//子组件
<template>
  <div>
    {{a}}
  </div>
</template>
<script>
export default {
  name:"HelloWorld",
  data () {
    return {
      a:'liudi'
    }
  },
}

第三种方法$childern

和$refs方法使用已将,不过将$refs替换为$children[index],其中index为子组件所在位置,但是vue不能保证子组件的顺序一定是书写的顺序,所以慎用,并且这种形成强耦合的写法也不太好

子传父

通过发布订阅模式,在vue源码的底层中,发布者和订阅者其实是一个人.通俗来说,子组件负责事件发布,同时子组件负责事件监听

//父组件用于接收
<button @click="fHandler" @fHandler2="getSHandler2"
>子组件给父组件传值</button>
methods:{
    getSHandler(e){//e就是子组件给父组件传递过来的值
      console.log(e);
    },
  getSHandler2(e){
    console.log('2',e);
  }
  }

//子组件用于传递
<button @click="fHandler">子组件给父组件传值</button>
 <button @click="$emit('fHandler2','didi2')">子组件给父组件传值2</button>
methods:{
    fHandler(){
      this.$emit('fhandler',{
        'f':1,
        'h':2
      });
    }
  }

点击按钮后,e的内容

 非父子

非父子组件之间没有联系,所以对于非父子组件传值,我们的思想就是通过父亲来转发,像App.vue和每个组件都有联系.

 vuex全局状态管理

provider +injected适合插件开发

$parent+$children不推荐,强耦合了

原文地址:https://www.cnblogs.com/liuXiaoDi/p/13100428.html