父子传值
父组件
<template>
<!-- 父组件 -->
<div class="home">
<!-- 调用的子组件 :动态传值 @子组件传的函数名 -->
<HelloWorld :msg="msg" @good="good"/>
</div>
</template>
//应用子组件路径
import HelloWorld from '@/components/HelloWorld.vue'
export default {
data(){
return{
msg:'这是父组件向子组件写的值'
}
}
//防止组件 从来进行调用
components: {
HelloWorld
},
methods:{
//应用函数
good(val){
//进行赋值
this.msg=val
}
}
}
</script>
子组件
<template>
<!-- 子组件 -->
<div class="hello">
<!-- 打印传的值 -->
<h1>{{ msg }}</h1>
<!-- 定义的函数方法 -->
<button @click="checkGoods">点击修改</button>
</div>
</template>
<script>
export default {
//用来接受父组件传递的值和类型
props: {
msg: String
},
methods:{
//函数名称
checkGoods(){
// 用this.$emit进行子向父传值
//good为函数名
this.$emit("good","子向父传的值")
}
}
}