vue组件通信

一.父组件传递数据给子组件

1.父组件App.vue

<template>
    <div id="app">
        <input type="button" value="按钮" @click="change()">
        <h1>{{msg}}</h1>
        <Menu :parentData="msg"></Menu>
    </div>
</template>

<script>
import Menu from "../components/Menu"
export default {
    name: 'app',
    data () {
        return {
            msg: '我是父组件',
        }
    },
    methods: {
        change(){
            this.msg = "数据被改变了"
        }
    },

    components: {
        Menu
    }
}
</script>

 

2.子组件Menu.vue想要拿到父组件数据: 使用props["parentDate"]

components/Menu.vue

<template>
    <div id="#child">
        <h1>我是子组件加载父组件的数据:{{parentData}}</h1>
    </div>
</template>
<script>
export default {
  data(){
      return {

      }
  },
  props: ["parentData"]
}
</script>

 

二.子组件更改父组件的数据

vue2.0子组件不能更改父组件的数据, 如果想的话,父组件传个对象给子组件
父组件每次传一个对象给子组件, 对象之间引用

1.父组件App.vue

<template>
    <div id="app">
        <input type="button" value="按钮" @click="changeParent()">
        <h1>{{giveDate.msg}}</h1>
        <Menu :parentData="giveDate"></Menu>
    </div>
</template>

<script>
import Menu from "../components/Menu"
export default {
    name: 'app',
    data () {
        return {
            giveDate: {
                msg: '我是父组件',
            }
        }
    },
    methods: {
        changeParent(){
            this.giveDate.msg = "数据被改变了"
        }
    },

    components: {
        Menu
    }
}
</script>

 

2.子组件Menu.vue

<template>
    <div id="#child">
        <h1>我是子组件加载父组件的数据:{{parentData.msg}}</h1>
        <input type="button" value="按钮" @click="changeChile()">
    </div>
</template>
<script>
export default {
    data(){
        return {
            
        }
    },
    methods: {
        changeChile(){
            this.parentData.msg = "111"
        }
    },

    props: ["parentData"]
}
</script>

  

posted @ 2018-02-24 14:24  AlanTao  阅读(416)  评论(0编辑  收藏  举报