一、父组件向子组件传递数据(props)
<template> <view class="container" style="background: #0062CC;"> <view class="child"> hi {{showModal}}</view> </view> </template> <script> export default { props: { showModal: { type: String, default: 'hello' } }, data() { return { }; },methods:{ } } </script> <style> </style>
<template> <view> <child :showModal="showModal"></child> </view> </template> <script> import child from "../../components/child.vue" export default { components: { child }, data() { return { showModal: " parent say" }; }, methods: { } } </script> <style> </style>
二、子组件向父组件传递数据(emit)
<template> <view> <child :showModal="showModal" @changes="childClick"></child> <view>{{parentValue}}</view> </view> </template> <script> import child from "../../components/child.vue" export default { components:{ child }, data() { return { showModal:" parent say", parentValue:'' }; },methods:{ childClick(e){ console.info(e); this.parentValue=e; } } } </script> <style> </style>
<template> <view class="container"> <button @tap="childClick" >点击我 </button> <view class="child"> hi {{showModal}}</view> </view> </template> <script> export default { props: { showModal: { type: String, default: 'hello' } }, data() { return { childdata:'child value' }; },methods:{ childClick(){ console.info(this.childdata); this.$emit("changes",this.childdata); } } } </script> <style> </style>
三、子组件与父组件数据同步(.sync)
<template> <view class="container" style="background: #0062CC;"> <button @tap="childClick" >点击我 </button> <view class="child"> hi {{showModal}}</view> <view>psync同步(child):{{syncDate}}</view> </view> </template> <script> export default { props: { showModal: { type: String, default: 'hello' }, syncDate: { type: String, default: 'hello' } }, data() { return { childdata:'child value' }; },methods:{ childClick(){ console.info(this.childdata); this.$emit("changes",this.childdata); } } } </script> <style> </style>
<template> <view> <child :syncDate.sync='syncDate' :showModal="showModal" @changes="childClick"></child> <view class="parent" style="background: #09BB07;"> <view>emit传值:{{parentValue}}</view> <input :value="syncDate" v-model="syncDate" style="background: #808080;" /> <view>psync同步(parent):{{syncDate}}</view> </view> </view> </template> <script> import child from "../../components/child.vue" export default { components: { child }, data() { return { showModal: " parent say", parentValue: '', syncDate: ' p syncDate' }; }, methods: { childClick(e) { console.info(e); this.parentValue = e; } } } </script> <style> </style>