步骤
1、ActiveUser.vue
<template>
<section>
<h2>{{ username }}</h2>
<h3>{{ userage }}</h3>
</section>
</template>
<script>
export default {
props: {
username: {
type: String,
required: true
},
userage: {
type: Number,
required: true
}
}
}
</script>
2、UserData.vue
<template>
<section>
<form @submit.prevent="submitData">
<input type="text" placeholder="Your Name" v-model="enteredName">
<input type="text" placeholder="Your Age" v-model="enteredAge">
<button>Set User Data</button>
</form>
</section>
</template>
<script>
export default {
data() {
return {
enteredName: '',
enteredAge: ''
}
},
methods: {
submitData() {
this.$emit('set-data', this.enteredName, this.enteredAge)
this.enteredName = ''
this.enteredAge = ''
}
}
}
</script>
3、main.js
import { createApp } from 'vue'
import App from './App.vue'
import ActiveUser from './components/ActiveUser.vue';
import UserData from './components/UserData.vue';
const app = createApp(App);
app.component('active-user', ActiveUser);
app.component('user-data', UserData);
app.mount('#app');
4、App.vue
<template>
<div>
<active-user :username="user.name" :userage="user.age"></active-user>
<user-data @set-data="setData"></user-data>
</div>
</template>
<script>
export default {
data() {
return {
user: {
name: 'Kevin Huang',
age: 28,
}
};
},
methods: {
setData(user, age) {
this.user.name = user;
this.user.age = +age;
}
},
}
</script>
<style>
html {
font-family: sans-serif;
}
section {
margin: 2rem auto;
max-width: 40rem;
border-radius: 12px;
border: 1px solid #ccc;
padding: 1rem;
}
</style>