首先是父组件里面的数据传递到子组件
这里用props,props有支撑物的意思,能够理解为桥梁。props要写在自组件里面。vue
先定义一个子组件,在组件中注册propsapp
<template> <div> <div>{{message}}(子组件)</div> </div> </template> <script> export default { props: { message: String //定义传值的类型<br> } } </script> <style> </style>
在父组件中,引入子组件,并传入子组件内须要的值this
<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>
注:这种方式只能由父向子传递,子组件不能更新父组件内的datacode
接下来是子组件的数据传递到父组件
这里用到了$emit ,emit有发射发出的意思,这就不难理解了component
tips: App.vue 父组件 / Hello.vue 子组件ip
父组件里面的内容
<!--App.vue :-->input
<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 :-->it
<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经过调用父的方法的方式完成了子向父的数据传递class