脚本宝典收集整理的这篇文章主要介绍了Vue 父子组件之间的数据通信--props,$emit,脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
首先是父组件里面的数据传递到子组件
这里用props,props有支撑物的意思,可以理解为桥梁。props要写在自组件里面。
先定义一个子组件,在组件中注册props
<template>
<div>
<div>{{message}}(子组件)</div>
</div>
</template>
<script>
export default {
props: {
message: String //定义传值的类型<br> }
}
</script>
<style>
</style>
在父组件中,引入子组件,并传入子组件内需要的值
<template>
<div>
<div>父组件</div>
<child :message="parentMsg"></child>
</div>
</template>
<script>
import child from './child' //引入child组件
export default {
data() {
return {
parentMsg: 'a message from parent' //在data中定义需要传入的值
}
},
components: {
child
}
}
</script>
<style>
</style>
注:这种方式只能由父向子传递,子组件不能更新父组件内的data
接下来是子组件的数据传递到父组件
这里用到了$emit ,emit有发射发出的意思,这就不难理解了
tips: App.vue 父组件 / Hello.vue 子组件
父组件里面的内容
<!--App.vue :-->
<template>
<div id="app">
<hello @newNodeEvent="parentLisen" />
</div>
</template>
<script>
import hello from './components/Hello'
export default {
name: 'app',
'components': {
hello
},
methods: {
parentLisen(evtValue) {
//evtValue 是子组件传过来的值
alert(evtValue)
}
}
}
</script>
子组件里面的内容
<!--Hello.vue :-->
<template>
<div class="hello">
<input type="button" name="" id="" @click="chilCall()" value="子调父" />
</div>
</template>
<script>
export default {
name: 'hello',
'methods': {
chilCall(pars) {
this.$emit('newNodeEvent', '我是子元素传过来的')
}
}
}
</script>
$emit通过调用父的方法的方式完成了子向父的数据传递
以上是脚本宝典为你收集整理的Vue 父子组件之间的数据通信--props,$emit全部内容,希望文章能够帮你解决Vue 父子组件之间的数据通信--props,$emit所遇到的问题。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。