Vue父子组件传值
首先创建基础项目
https://blog.csdn.net/sunt2018/article/details/102697487
然后写一个父子组件
App.vue
<template>
<div id="app">
<!-- 导入父组件 -->
<!-- 默认规则 必须大写MP 使用小写m-p,-隔开 -->
<m-parent></m-parent>
</div>
</template>
<script>
import MParent from './views/Parent' //d导入父组件
export default {
components:{
MParent,//注册父组件
},
}
</script>
在views 创建父子组件
Parent.vue
首字母大写,也是大多数默认规则
<template>
<div>
<h1>Parent父组件</h1>
<m-child></m-child>
</div>
</template>
<script>
import MChild from './Child'
export default{
components:{
MChild,
},
}
</script>
<style scoped>
</style>
Child.vue
<template>
<div>
<h3>child组件</h3>
</div>
</template>
<script>
export default{
}
</script>
<style>
</style>
父子组件间的传值
props/$emit
$parent/children
$ref
第一种传值方式,绑定属性
<!-- 父组件中的 子组件上写 -->
<m-child v-bind:msg="'from Parent msg'"></m-child>
<!-- 使用v-bind , 字段参数是msg,传入内容为字符串 -->
<!-- 子组件中接收 -->
<template>
<div>
<h3>child</h3>
<!-- 使用 -->
<h5>{
{msg}}</h5>
</div>
</template>
<script>
export default{
props:{//接收参数
msg:{
type:String,//类型
default:'' // 默认值
}
}
}
</script>
反向传值,子组件向父组件传值,一般是通过事件触发
<!-- 子组件写一个点击事件 -->
<button @click="passMsg">走你</button>
<script>
export default{
methods:{
passMsg(){
this.$emit('showMsg','i am from child')
// 传一个自定义的事件 showMsg,值是 i am from child
}
}}
</script>
<!-- 父组件,使用@事件=“事件” 去监听 -->
<m-child v-bind:msg="'from Parent msg'" @showMsg="showMsg"></m-child>
export default{
data(){
return {
msg:'',// 通过msg去接收监听的参数
}
},
components:{
MChild,
},
methods:{//监听方法,val是子组件传入的值
showMsg(val){
this.msg = val
}
}
}
</script>
第二种方法,使用 $parent/ $children
需要创建一个钩子
mounted(){
this.$children[0].msg //要手动寻找索引,然后再找信息
//还可以触发方法
}
第三种方法 refs
this.refs.child
和第二种方法一样,都是一个数组
需要先通过索引找到需要的子组件,然后调用里面的值或则和函数
还没有评论,来说两句吧...