目录
(1)通过调用子组件方法实现传参
父组件的方法中用 this.$refs.refName.getMethod 去调用子组件的getMethod方法。
父组件将参数params传入数据给子组件即this.$refs.refName.getMethod(params),子组件的getMethod需要设置一个参数接收,即getMethod(data)。
子组件向父组件返回参数,用 this.$emit(“backOkHandel”,params) 去返回params给父级页面的子组件backOkHandel定义的方法。
<!----父组件------!>
<template>
<div>
<City ref="setCitySelectModalRef" @backOkHandel="backOkHandel"></City>
</div>
<div>{{ init.children }}</div>
</template>
<script>
// 引入子组件
import City from "@_src/components/City";
export default {
data() {
return {
init:{
model:'我是父组件的参数',
children:''
}
}
},
created() {
this.getLoadData()
},
methods: {
// 调用子组件的方法,并将init.model代入
getLoadData() {
this.$refs.setCitySelectModalRef.getChildrenData(init.model)
},
// 接收子组件返回的参数
backOkHandel(params):{
this.init.children = params
}
},
components: {
City
}
}
</script>
<!----子组件City------!>
<template>
<div>
{{ init.params }}
</div>
// 自定义按钮,点击change触发send方法
<lzy-button @change="send">发送<lzy-button>
</template>
<script>
export default {
data() {
return {
init:{
params:'',
back:'收到了,谢谢'
}
}
},
methods: {
// 接收来自父组件的参数params
getChildrenData(params) {
this.init.params = params
},
// send触发时,将init.back返回父组件
send(){
this.$emit("backOkHandel",this.init.back)
}
}
}
</script>
(2)使用props传递参数
首先父级页面引用子组件时,要通过冒号加属性名定义参数
<!----父组件------!>
<template>
<div>
<p>我是父组件,传递消息给子组件,需要传递的消息在下面输入:</p>
<city :id="id"></city>
</div>
</template>
<script>
// 引入子组件
import City from "@_src/components/City";
export default {
name: "parent",
data(){
return{
id:'1000000'
}
},
components : {
city
}
}
</script>
<style scoped>
</style>
<!----子组件City------!>
<template>
<div>
<p>我是子组件,接收来自父组件的信息:{{id}}</p>
</div>
</template>
<script>
export default {
name: "child",
props: ['id']
}
</script>
<style scoped>
</style>
以上也可以组合使用
<dataTable :id="id" :type="type" ref="setDataTableModalRef" @backOkHandel="backOkHandel" @backCleanHandel="backCleanHandel"/>