vue中父组件像子组件传值:* *用props,如下:
父组件中:
<template>
<div>
<firstchildren :Msg="msg"></firstchildren>
</div>
</template>
<script>
import firstchildren from "./children/firstchildren"
export default {
data(){
return {
msg:'我是父组件,我要传递给子组件值'
}
},
components:{
firstchildren
}
}
</script>
<style scoped>
</style>
子组件中:
<template>
<div>
{{Msg}}
</div>
</template>
<script>
export default {
data(){
return{
}
},
props:
{
Msg:String
}
}
</script>
<style scoped>
</style>
**
2.父组件获取子组件数据,父组件通过$refs获取子组件的数据和方法
**
子组件:
<template>
<div>
</div>
</template>
<script>
export default {
data(){
return{
dataList:"我是子组件"
}
},
methods:{
getmsg(){
console.log("hahahahahah")
}
}
}
</script>
<style scoped>
</style>
父组件:
<template>
<div>
<firstchildren :Msg="msg"></firstchildren>
<parentnal ref="lili"></parentnal>
<div>{{tilte}}</div>
<button @click="getnail">按钮</button>
</div>
</template>
<script>
import firstchildren from "./children/firstchildren"
import parentnal from './children/parentnal'
export default {
data(){
return {
msg:'我是父组件,我要传递给子组件值',
tilte:''
}
},
components:{
firstchildren,
parentnal
},
mounted(){
this.tilte=this.$refs.lili.dataList;
},
methods: {
getnail(){
this.$refs.lili.getmsg()
}
},
}
</script>
<style scoped>
</style>
3.子组件主动获取父组件的数据,直接在子组件中使用this.$parent.XX,不需要做任何多余操作
父组件
<template>
<div>
<firstchildren :Msg="msg"></firstchildren>
<parentnal ref="lili"></parentnal>
<div>{{tilte}}</div>
<button @click="getnail">按钮</button>
<second></second>
</div>
</template>
<script>
import firstchildren from "./children/firstchildren"
import parentnal from './children/parentnal'
import second from './children/second'
export default {
data(){
return {
msg:'我是父组件,我要传递给子组件值',
tilte:''
}
},
components:{
firstchildren,
parentnal,
second
},
mounted(){
this.tilte=this.$refs.lili.dataList;
},
methods: {
getnail(){
this.$refs.lili.getmsg()
}
},
}
</script>
<style scoped>
</style>
子组件:
<template>
<div>
<div>{{datalilist}}</div>
<button @click="getment">按钮2</button>
</div>
</template>
<script>
export default {
data(){
return{
datalilist:''
}
},
mounted(){
this.datalilist=this.$parent.msg
},
methods: {
getment(){
this.$parent.getnail()
}
},
}
</script>
<style scoped>
</style>