【父子组件传值】Vue子父组件传值的三种方法
•
前端
父组件向子组件传值: props-父组件给子组件传输数据和验证
1.父组件的代码示例
父组件
// 引用子组件
// 导入子组件
import Dialog from '@/components/Dialog.vue'
export default {
name: 'HomeView',
components: { Dialog },
data () {
return {
fatherData: '父组件的值',
}
}
}
2.子组件的代码示例
子组件
//展示父组件数据
{{fatherData}}
export default {
data () {
return {
childrenData: '子组件自己的数据'
}
},
//props的基本用法是父组件给子组件传输数据和验证
props: {
//父组件数据
fatherData: {
type: String
}
}
}
子组件向父组件传值:this.$emit()-子组件可以使用 $emit,让父组件监听到自定义事件
1.父组件的代码示例
父组件
// 引用子组件
//展示子组件的值
{{ receiveData }}
// 导入子组件
import Dialog from '@/components/Dialog.vue'
export default {
name: 'HomeView',
components: { Dialog },
data () {
return {
fatherData: '父组件的值',
receiveData:''
}
},
methods: {
//接收子组件传过来的数据
tranferData(val){
console.log('子组件向父组件传过来的值:',val)
this.receiveData = val
}
}
}
2.子组件的代码示例
子组件
子向父传值
export default {
data () {
return {
childrenData: '子组件的值'
}
}
},
methods:{
tranfer(){
this.$emit('tranferData',this.childrenData)
}
}
}
通过
r
e
f
s
调用子组件的值
−
用
t
h
i
s
.
refs调用子组件的值-用this.
refs调用子组件的值−用this.refs 获取到的是组件实例,可以使用组件的所有方法
1.父组件的代码示例
父组件
// 引用子组件
通过refs拿到子组件的值
refs拿到子组件的值
// 导入子组件
import Dialog from '@/components/Dialog.vue'
export default {
name: 'HomeView',
components: { Dialog },
data () {
return {
fatherData: '父组件的值',
}
},
methods:{
toGet(){
// 通过refs调用子组件的值(childrenData)
const data = this.$refs.dialogData.childrenData
alert(data)
// 通过refs调用子组件的值(childrenWay())
const way = this.$refs.dialogData.childrenWay()
alert(way)
}
}
}
2.子组件的代码示例
子组件
export default {
data () {
return {
childrenData: '子组件自己的数据'
}
},
methods:{
childrenWay(){
alert('父组件调用子组件的方法')
}
}
}
本文来自网络,不代表协通编程立场,如若转载,请注明出处:https://www.net2asp.com/84b904da47.html
