vue2 组件通讯

1,父子,通过props 传递

子组件生命,父组件传递!

2, 兄弟组件通讯,用this.$parent通讯

App.vue

<template>
  <div id="app">
    <!-- <div id="nav">
      <router-link to="/">Home</router-link> |
      <router-link to="/about">About</router-link>
    </div>
    <router-view/> -->
    java
    <!-- <Child name = "action"></Child> -->
    <Child ></Child>
    <Detail></Detail>
  </div>
</template>

<script>
import Child from '@/components/child.vue'
import Detail from "@/components/detail.vue"
import { connect } from 'tls';
export default {
  components:{
    Child,
    Detail
  },
  methods:{
    show(message){
      console.log("..." + message)
    }
  }
}
</script>



<style lang="scss">
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
}

#nav {
  padding: 30px;

  a {
    font-weight: bold;
    color: #2c3e50;

    &.router-link-exact-active {
      color: #42b983;
    }
  }
}
</style>

两个孩子 child.vue

<template>
    <div class="app">
        child
        {
   
   {name}}

        <p @click="go">go...</p>
    </div>
</template>


<script>
import {Type} from "@/constants/common.js"
export default {
    props:{
        name:{
            type:String,
            require:true
        }
    },
    methods:{
        go(){
            console.log("hello")
            this.$emit(Type,"vue is so easy!")
        }
    },
    mounted(){
        this.$parent.$on(Type,function(msg){
            console.log(msg)
        })
    }
}
</script>

<style >

</style>

detail.vue

<template>
    <div class="app">
        child
        dog small dog! small cat!
        <button @click="smile">$parent</button>
    </div>
</template>


<script>
import {Type} from "@/constants/common.js"
export default {
    props:{
        
    },
    methods:{
        [Type](){
            console.log(".....")
            this.$parent.$emit(Type,"smile is so easy!")
        }
    }
}
</script>

<style >

</style>

中间遇到一个常量文件

common.js

export const Type = "smile";

我的理解很简单,就是俩兄弟通讯,通过父亲来通讯

这个猜疑链就是如果主君开始猜疑臣子,那么臣子要么被差一点被干掉,要么好一点卸甲归田(极少数),要么干脆造反。

如果答主看过琅琊榜,那可能会更形象一些。

琅琊榜一的设定就是这样,主人公一家对皇帝忠心耿耿,立下赫赫战功,最终被诬杀。甚至杀死自己亲儿子的时候也毫不犹豫。

因为你威胁到我的皇位了,我不知道你有没有反叛的心,但是你有反叛的能力。这个猜疑链在皇上心中已经形成,因为人心隔肚皮,皇帝永远不知道臣子到底会怎么想。

所以历史上聪明一点的人,一般就主动交权来打破猜疑链了。通常也会有个好下场,比如说曾国藩。

如果不交呢?

我不知道皇帝有没有怀疑我,虽然我战功赫赫,可能已经功高震主,他也早就会有防备之心,可能稍有风吹草动就会造反了。

所以,君疑臣则诛 臣疑君则反

这就是古代帝王和臣子的猜疑链,历史上有很多次外患还未解除,就开始大杀功臣的事情,比如太平天国,比如南宋王朝。

各种造反也是比比皆是。比如玄武门兵变,兄弟三人血刃相见。再比如朱棣造反

其他通讯方式

vuex 还有$bus 其核心原理,还是观察者模式,我就不写了!

有兴趣的伙伴可以看看provide 和reject 

猜你喜欢

转载自blog.csdn.net/qq_15009739/article/details/113790159