Vue里父子组间的通讯
父组件代码
<template><div>
<child @child-say="listenToBoy" :mes=count></child>
<p>Do you like me?{{this.word}}</p>
</div>
</template>
<script>
import child from '@/components/child.vue'
export default {
name: "parent",
data() {
return {
count: 0,
word: ''
};
},
components: {
child
},
methods:{
listenToBoy(text){
if (!this.word){
this.word = text
console.log('111')
}else{
this.word = ''
console.log('else')
}
}
}
}
</script>
<style lang="css" scoped>
</style>
子组件代码
<template><div>
<p>{{message}}</p>
<button @click="add">add</button>
<button @click="onClickMe">Click</button>
</div>
</template>
<script>
export default {
name: "child",
data () {
return {
message: this.mes,
text: 'I love you'
};
},
props: ['mes'],
methods: {
add (){
this.message ++
},
onClickMe(){
this.$emit('child-say', this.text)
}
}
}
</script>
<style lang="css" scoped>
</style>
1.实现了将count的值通过props将父组件的值给子组件,用法:在父组件中的子组件标签绑定某个属性将要传的值跟在其后(如:mes=count,给子组件识别用的)传递,子组件用props:['mes']接收,子组件调用用this.mes
2.子组件向父组件传值this.$emit(),用法:父组件监听某个属性(如@child-say='listenToBoy()')的方法,父组件方法中的形参来接收子组件传过来的值(如listenToBoy(text)),
子组件在某处触发this.$emit('child-say',this.text)
以上是 Vue里父子组间的通讯 的全部内容, 来源链接: utcz.com/z/375625.html