父组件向子组件传值
组件实例定义方式,注意:一定要使用props属性来定义父组件传递过来的数据

<script> // 创建 Vue 实例,得到 ViewModel var vm = new Vue({ el: '#app', data: { msg: '这是父组件中的消息' }, components: { son: { template: '<h2>这是子组件 --- {{finfo}}</h2>', props: ['finfo'] } } }); </script>使用v-bind或简化指令,将数据传递到子组件中:<div id="app"> <son :finfo="msg"></son> </div>

子组件向父组件传值
原理:父组件将方法的引用,传递到子组件内部,子组件在内部调用父组件传递过来的方法,同时把要发送给父组件的数据,在调用方法的时候当作参数传递进去;
父组件将方法的引用传递给子组件,其中,getMsg是父组件中methods中定义的方法名称,func是子组件调用传递过来方法时候的方法名称

<son @func="getMsg"></son>子组件内部通过this.$emit('方法名', 要传递的数据)方式,来调用父组件中的方法,同时把数据传递给父组件使用<div id="app"> <!-- 引用父组件 --> <son @func="getMsg"></son> <!-- 组件模板定义 --> <script type="x-template" id="son"> <div> <input type="button" value="向父组件传值" @click="sendMsg" /> </div> </script> </div> <script> // 子组件的定义方式 Vue.component('son', { template: '#son', // 组件模板Id methods: { sendMsg() { // 按钮的点击事件 this.$emit('func', 'OK'); // 调用父组件传递过来的方法,同时把数据传递出去 } } }); // 创建 Vue 实例,得到 ViewModel var vm = new Vue({ el: '#app', data: {}, methods: { getMsg(val){ // 子组件中,通过 this.$emit() 实际调用的方法,在此进行定义 alert(val); } } }); </script>组件中data和props的区别评论列表案例目标:主要练习父子组件之间传值使用 this.$refs 来获取元素和组件<div id="app"> <div> <input type="button" value="获取元素内容" @click="getElement" /> <!-- 使用 ref 获取元素 --> <h2 ref="myh2">这是一个大大的H1</h2> <hr> <!-- 使用 ref 获取子组件 --> <my-com ref="mycom"></my-com> </div> </div> <script> Vue.component('my-com', { template: '<h6>这是一个子组件</h6>', data() { return { name: '子组件' } } }); // 创建 Vue 实例,得到 ViewModel var vm = new Vue({ el: '#app', data: {}, methods: { getElement() { // 通过 this.$refs 来获取元素 console.log(this.$refs.myh2.innerText); // 通过 this.$refs 来获取组件 console.log(this.$refs.mycom.name); } } }); </script>