下載vue-cli:npm install -g vue-cli
vue init webpack vue-demo
cd vue-demo
npm install
npm run dev
<template> <p> <p v-for="(item,key) of c" :key="key"> {{key}}: {{item}} </p> </p> </template> <script> export default { name: 'child', props: { c: Array } } </script> <style scoped> </style>
v-bind指令綁定c。子元件透過props就可以接受到這個父元件傳遞的值。
<template> <p class="hello"> <home-child v-bind:c="c"></home-child> </p> </template> <script> import HomeChild from '@/components/common/Child' export default { name: 'home', components: { HomeChild }, data () { return { c:[1,2,3] } } } </script> <style scoped> </style>
#給按鈕綁定點擊事件ChildClick
<template> <p> <p v-for="(item,key) of c" :key="key"> {{key}}: {{item}} </p> <button v-on:click="ChildClick">点击向父组件传值</button> <span>{{data}}</span> </p> </template> <script> export default { name: 'child', props: { c: Array, data: String }, methods: { ChildClick: function () { this.$emit("ListenChild","I am child.vue") } } } </script> <style scoped> </style>
<template> <p class="hello"> <home-child v-bind:c="c" :data="data" v-on:ListenChild="ShowChild"></home-child> </p> </template> <script> import HomeChild from '@/components/common/Child' export default { name: 'Home', components: { HomeChild }, data () { return { c:[1,2,3], data: " " } }, methods: { ShowChild: function (data) { this.data = data console.log("data:" + data) } } } </script> <style scoped> </style>
點擊按鈕後:
以上是Vue子元件與父元件之間的通訊(附代碼)的詳細內容。更多資訊請關注PHP中文網其他相關文章!