1.父傳子
父組件:
<template> <div class="box"> <child :fMessage="data2"></child> <Button type="primary" @click="chua">傳值</Button> </div> </template> <script> import child from '../../components/demo3/child.vue' export default { components: { child }, name: 'demo3', computed: { }, data () { return { data2: '父組件數據data2' } }, methods: { chua () { this.data2 = 'wangjiale' } } } </script>
子組件:
<template> <div> <p>第二個數據:{{fMessage}}</p> </div> </template> <script> export default { name: 'child', props: ['fMessage'], data () { return{ } }, created () { } } </script>
樣式展示
傳值之前:
傳值以後:
2.子傳父
父組件:
<template> <div> <child-5 @chuachua="changeName"></child-5> <div>{{name}}</div> </div> </template> <script> import child5 from '../../components/demo5/child5.vue' export default { components: { child5 }, name:'demo5', data () { return { name:'' } }, methods: { changeName: function (name) { this.name = name } } } </script>
子組件:
<template> <div> <Button type="primary" @click="chua">傳值給父組件</Button> </div> </template> <script> export default { name: 'child5', data () { }, methods: { chua () { this.$emit('chuachua', 'wangjiale') } } } </script>
樣式展示
傳值之前:
傳值以後:
注:
this.$emit('chuachua', 'wangjiale')
此行的第二個參數爲子組件向父組件傳的值