共计 1726 个字符,预计需要花费 5 分钟才能阅读完成。
父组件向子组件传值: props- 父组件给子组件传输数据和验证
1. 父组件的代码示例
template>
div>父组件/div>
Dialog :fatherData="fatherData">/Dialog>
/template>
script>
import Dialog from '@/components/Dialog.vue'
export default {
name: 'HomeView',
components: { Dialog },
data () {
return {
fatherData: '父组件的值',
}
}
}
/script>
2. 子组件的代码示例
template>
div>
div>子组件/div>
div>
{{fatherData}}
/div>
/div>
/template>
script>
export default {
data () {
return {
childrenData: '子组件自己的数据'
}
},
props: {
fatherData: {
type: String
}
}
}
/script>
子组件向父组件传值:this.$emit()- 子组件可以使用 $emit, 让父组件监听到自定义事件
1. 父组件的代码示例
template>
div>父组件/div>
Dialog @tranferData="tranferData">/Dialog>
div>{{ receiveData }}/div>
/template>
script>
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
}
}
}
/script>
2. 子组件的代码示例
template>
div>
div>子组件/div>
el-button @click="tranfer">子向父传值/el-button>
/div>
/template>
script>
export default {
data () {
return {
childrenData: '子组件的值'
}
}
},
methods:{
tranfer(){
this.$emit('tranferData',this.childrenData)
}
}
}
/script>
通过
r
e
f
s
调用子组件的值
−
用
t
h
i
s
.
refs 调用子组件的值 - 用 this.
refs调用子组件的值 − 用this.refs 获取到的是组件实例, 可以使用组件的所有方法
1. 父组件的代码示例
template>
div>父组件/div>
Dialog ref='dialogData'>/Dialog>
div>通过 refs 拿到子组件的值/div>
el-button @click="toGet">refs 拿到子组件的值/el-button>
/template>
script>
import Dialog from '@/components/Dialog.vue'
export default {
name: 'HomeView',
components: { Dialog },
data () {
return {
fatherData: '父组件的值',
}
},
methods:{
toGet(){
const data = this.$refs.dialogData.childrenData
alert(data)
const way = this.$refs.dialogData.childrenWay()
alert(way)
}
}
}
/script>
2. 子组件的代码示例
template>
div>
div>子组件/div>
/div>
/template>
script>
export default {
data () {
return {
childrenData: '子组件自己的数据'
}
},
methods:{
childrenWay(){
alert('父组件调用子组件的方法')
}
}
}
/script>
原文地址: 【父子组件传值】Vue 子父组件传值的三种方法
正文完