Vue.js父子组件传值

父组件向子组件传值:

<!--父组件通过属性传递msg给子组件,常量和变量方式不同-->
<helloworld msg="常量值"> </helloworld>
<helloworld v-bind:msg="变量名"> </helloworld>
<!--子组件接收,msg可以在页面中直接使用,js中通过this.msg调用-->
<script>
  export default {
    name: 'HelloWorld',
    data() {
      return {
        message:"啦啦啦"
      }
    },
//在props中声明
    props:['msg']
  }
</script>

子组件向父组件传值:

<!--子组件触发事件时通过$emit传递消息-->
<template>
  <div>
    我是子组件
    <button v-on:click="callPhone">疯狂打call</button>
  </div>
</template>

<script>
  export default {
    name: "child",
    data() {
      return {
        news: "有人打我!!!"
      }

    },
    methods: {
      callPhone: function () {
        this.$emit('事件名', this.news)

      }
    }
  }
</script>
<!--父组件通过v-on:"事件名"指令接收-->
<child v-on:call="phone"></child>

export default {
    el:"#app",
    methods: {
      phone:function (msg) {
        alert(msg)
      }
    }
  }
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容