1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87
| <!--App.vue父组件--> <template> <!--加载组件第三步:显示子组件--> <h3>我是父组件</h3> <div>子组件向父组件传递的数据:{{msgFromChild}}</div> <MyComponent :msg="message" @OnChild="GetData"/> </template>
<script> //加载组件第一步:引入子组件 import MyComponent from "@/components/MyComponent"
export default { name: 'App', //加载组件第二步:挂载子组件 components: { MyComponent }, data(){ return{ message:"I am your father.", msgFromChild:"" } }, methods:{ //data即从子组件接收到的数据(其会作为GetData的参数) GetData(data){ console.log(data); this.msgFromChild=data } } } </script>
<style> #app { font-family: Avenir, Helvetica, Arial, sans-serif; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; text-align: center; color: #2c3e50; margin-top: 60px; } h3{ color: red; font-weight: bolder; } </style>
<!--MyComponent.vue子组件--> <template> <h3>我是子组件</h3> <div>父组件向子组件传递的值是:{{msg}}</div> <button @click="SendHandle">子组件将值传递给父组件</button> </template>
<script> export default { name: "MyComponent", data(){ return { messagePlus:"I am your children." } }, props:{ msg:{ type:String, default:"" } }, methods:{ SendHandle(){ this.$emit("OnChild",this.messagePlus) } } } </script>
<!--scoped代表当前样式只在当前组件中生效--> <style scoped> h3{ color: red; font-weight: bolder; } </style>
|