美文网首页
Vue.js父子组件传值

Vue.js父子组件传值

作者: baiduo | 来源:发表于2018-03-29 18:42 被阅读0次

父组件向子组件传值:

<!--父组件通过属性传递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)
      }
    }
  }

相关文章

网友评论

      本文标题:Vue.js父子组件传值

      本文链接:https://www.haomeiwen.com/subject/xttvcftx.html