父组件传递数据到子组件
父组件获取到数据后,通过v-bind将属性绑定到子组件标签上
例如子组件名为<myTest>
注意:定义组件时组件名不能与H5标签名重复否则会报错:Do not use built-in or reserved HTML elements as component id: xxx
将子组件文件导入父组件
import myTest from './components/myTest/myTest.vue'
在父组件中注册
export default { data() { return { goods: {} } }, created() { this.$http.get('/api/goods').then((response) => { response = response.body this.good = response.data }) }, components: { myTest } }
在父组件中加入子组件myTest
<template> <div id="app"> <myTest :goods="goods"></myTest> </div> </template>
在子组件中通过props属性接收父组件传递过来的数据
export default { props: { goods: { type: Object } } }
在子组件中绑定数据
<template> <div>{{goods.name}}</div> </template>
子组件传递数据到父组件
子组件主要通过事件传递数据给父组件
子组件中定义一个按钮,通过v-bind绑定一个点击事件,事件名为toParent
在methods中通过emit将数据传递出去,第一个参数是传递的方法,第二个参数是传递的数据
<template> <div> <button @click="toParent">向父组件传递数据</button> </div> </template> <script type="text/ecmascript-6"> export default { methods: { toParent: function () { this.$emit('sendMsg', '来自子组件的信息') } } } </script>父组件中通过v-bind绑定子组件传递过来的方法,并且定义一个方法
在methods中对传递过来的数据进行处理,参数data就是子组件传递进来的数据
<template> <div id="app"> <myTest @sendMsg="showMsg"></myTest> </div> </template> <script type="text/ecmascript-6"> import myTest from './components/myTest/myTest.vue' export default { methods: { showMsg: function (data) { console.log(data) } }, components: { myTest } } </script>