MyChild.vue
Note:我们需要增加如下语句来更新props:msg
this.$emit('update:msg', ' after click');
第二个参数是要更新的内容。
<template>
<div>
<h1>MyChild</h1>
<p>{{ msg }}</p>
<button @click="changeMsg">Change Msg</button>
</div>
</template>
<script>
export default {
name: 'MyChild',
props: {
msg: {
type: String,
default: 'hello from my child'
}
},
methods: {
changeMsg() {
this.$emit('update:msg', ' after click');
}
}
}
</script>
<style scoped>
h1 {
color: blue;
}
</style>
App.vue
Note:
- The code is added under the key word "NEW"
- :msg 等同于v-bind,将MyChild props msg 跟pmsg(App.vue 下的变量)绑定,用于动态更新msg
<template>
<img alt="Vue logo" src="./assets/logo.png">
<!--<HelloWorld msg="Welcome to Your Vue.js App"/>-->
<!--NEW-->
<MyChild :msg="pmsg" @update:msg="pmsg = $event"/>
</template>
<script>
// NEW
import MyChild from './components/MyChild.vue';
//import HelloWorld from './components/HelloWorld.vue'
export default {
name: 'App',
components: {
//HelloWorld
// NEW
MyChild
},
// NEW
data() {
return {
pmsg: "hello from parent"
}
}
}
</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;
}
</style>