vue父子组件传值:父组件向子组件传值用的是props
1.定义父组件
1)父组件想要向子组件传值时,那么需要在子组件引入的地方绑定一个属性,属性值就是要传的数据,并且要在父组件中引入子组件。
2)这个自定义属性的属性值是用来存放父组件向子组件传递的数据。
3)在这里,name即是要传的数据,需要在data定义,所以当传递的数据时字符串类型时,可以在data定义为name:''
父组件如下:
2.定义子组件
1)子组件使用props属性接收父组件传递过来的值。
写法是:
props:{父组件自定义的属性:该值的类型,required:true}
所以在这里是:
props: {inputName: String,required: true}
2)然后可以直接在页面上以这个形式“{{}}”引用。
子组件如下:
代码:
1.父组件代码如下:
<template><div>父组件:<input type="text" v-model="name"><br><br><!-- 引入子组件 --><child :inputName="name"></child></div></template><script>import child from './child'export default {components: {child},data () {return {name: ''}}}</script>
2.子组件代码
<template><div>子组件:<span>{{inputName}}</span></div></template><script>export default {// 接受父组件的值props: {inputName: String,required: true}}</script>