• Vue组件之间的通信


    项目中写组件一般是在component文件夹下,注册过的组件想要全局使用则需要在main.js中引入,局部使用的话就在需要的地方引入。我是全局引入:

    (一)父组件向子组件传值(子组件通过props接收父组件的值)

    父组件代码:app.vue

    <template>
      <div id="app">
        <img src="./assets/logo.png">
        <router-view/>
        <son :message="msg"></son>
      </div>
    </template>
    
    <script>
    export default {
      name: 'App',
      data(){
          return {
            msg: "我是父组件的数据"
          }
      }
    }
    </script>

    子组件代码:SonComponent.vue

    <template>
      <section>
        <h1>{{title}}</h1>
        <div>{{message}}</div>
      </section>
    </template>
    <script>
    export default {
      name: 'SonComponent',
      data () {
        return {
          title: '子组件页面'
        }
      },
      props:['message']
    }
    </script>

    效果如下:

     

    (二)子组件→父组件通信(子组件通过$emit( eventName)来触发一个事件)

     父组件代码:app.vue

    <template>
      <div id="app">
        <img src="./assets/logo.png">
        <router-view/>
        <son-btn @connect="say"></son-btn>
      </div>
    </template>
    
    <script>
    export default {
      name: 'App',
      data(){
          return {
            msg: "我是父组件的数据"
          }
      },
      methods:{
        say(arg){
          console.log(`大家好,我监听到了事件connect的触发,并且接收到了参数${arg[0]}`);
        }
      }
    }
    </script>

    子组件代码:SonComponent.vue

    <template>
      <section>
        <h1>{{title}}</h1>
        <button @click="send">按钮</button>
      </section>
    </template>
    <script>
      export default {
        name: 'Son1Component',
        data () {
          return {
            title: '子按钮'
          }
        },
        methods:{
            send(){
              this.$emit('connect',[1,2,3]);
            }
        }
      }
    </script>

    效果如下: 

     (三)非父子组件的通信

    除了父子组件的相互通信,非父子关系的组件该如何通信,我们可以巧妙地利用一个空的vue实例来作为一个中央事件总线。

    但是在实际开发中,我们不会这么做,我们会使用专门用于状态管理的 vuex ,关于vuex后续更新。

  • 相关阅读:
    ubuntu中,update,upgrade出现问题总结
    Xshell7连接kali linux(2021.9.13)
    pycharm安装igraph,简单实例(2021.8.21)
    mininet可视化(2021.6.25)
    冷知识:你会搜索信息吗
    论文写作注意事项
    onenote2016怎么自动备份笔记本到本地?
    Cbench、Scapy、sflow、iperf——学习中
    Zookeeper、Docker——学习中
    OpenStack管理、KVM、ClouldSim部署——学习中
  • 原文地址:https://www.cnblogs.com/linjiu0505/p/10875770.html
Copyright © 2020-2023  润新知