一、Vue2
1.父传子
在App.Vue中,写
<template>
<div id="app">
<MyHeader class="mh" :msg="msg"/>
</div>
</template>
<script>
import MyHeader from "./components/MyHeader.vue";
export default{
data(){
return{
msg:'hello vue'
}
},
components:{
MyHeader,
}
}
</script>
在MyHeader.Vue中,写
<template>
<div>
{{msg}}
</div>
</template>
<script>
export default {
props:['msg'],
}
</script>
2.子改父
(一)方法一(动态属性):
在App.Vue中,写
<template>
<div id="app">
<MyHeader class="mh" :msg="msg" :changeMsg="changeMsg"/>
</div>
</template>
<script>
import MyHeader from "./components/MyHeader.vue";
export default{
data(){
return{
msg:'hello vue'
}
},
methods:{
changeMsg(){
this.msg = 'hello gis'
}
},
components:{
MyHeader,
}
}
</script>
在MyHeader.Vue中,写
<template>
<div>
{{msg}}
<button @click="change">按钮</button>
</div>
</template>
<script>
export default {
props:['msg','changeMsg'],
methods:{
change(){
this.changeMsg()
}
}
}
</script>
(二)方法二(动态事件):
在App.Vue中,写
<template>
<div id="app">
<MyHeader class="mh" :msg="msg" @changeMsg="changeMsg"/>
</div>
</template>
<script>
import MyHeader from "./components/MyHeader.vue";
export default{
data(){
return{
msg:'hello vue'
}
},
methods:{
changeMsg(){
this.msg = 'hello gis'
}
},
components:{
MyHeader,
}
}
</script>
在MyHeader.Vue中,写
<template>
<div>
{{msg}}
<button @click="change">按钮</button>
</div>
</template>
<script>
export default {
props:['msg'],
methods:{
change(){
this.$emit('changeMsg')
}
}
}
</script>
二、Vue3(与Vue2的区别部分)
子改父:
在App.Vue中,写
<template>
<div>
<Child :msg="msg" @changeMsg="changeMsg"/>
</div>
</template>
<script>
import { ref } from 'vue';
import Child from './Child.vue'
export default {
setup(){
let msg = ref('hello vue3')
function changeMsg(){
msg.value = 'easy vue3'
}
return{
msg,
changeMsg
}
},
components:{
Child,
}
}
</script>
在Child.vue中,写
<template>
<div>
{{ msg }}
<button @click="change">点击</button>
</div>
</template>
<script>
export default {
props:['msg'],
emits:['changeMsg'], /* 更直观地获取绑定的自定义事件 */
setup(props,ctx){
console.log(props.msg);
function change(){
ctx.emit('changeMsg')
}
return {
change
}
}
}
</script>