<template> <div id="parent"> <h3>显示子组件</h3> <item1></item1> <h3>--------------</h3> <h3>取当前组件中data的值:</h3> <h1>{{ msg }}</h1> <h3>1.父组件传值给子组件--------------</h3> 父组件:<input type="text" v-model="testname"><br/> <h3>以下子组件的值,来自于父组件的传入:</h3> <child1 :inputName="testname"></child1><br/> <h3>2.子组件向父组件传值</h3> <h3>childByValue v-on方法监听子组件的状态</h3> <child1 v-on:childByValue="childByValue"></child1> <h3>子组件传来的值:{{tempChildValue}}</h3> </div> </template> <script> import Item1 from './Item1' import Child1 from './Child1' export default { name: 'HelloWorld', data () { return { msg: 'Welcome! this is a Czh Vue.js App', testname:'', tempChildValue:'' } }, components: { Item1: Item1, Child1:Child1, }, methods:{ childByValue:function (childValue) { this.tempChildValue=childValue } }, } </script> <!-- Add "scoped" attribute to limit CSS to this component only --> <style scoped> h1, h2 { font-weight: normal; } ul { list-style-type: none; padding: 0; } li { display: inline-block; margin: 0 10px; } a { color: #42b983; } </style>
以下是子组件:
<template> <div> 子组件:<span>{{inputName}}</span><br/><br/> <!--定义一个方法,用来向父组件传值--> <input type="button" value="点击触发子向父传" @click="childclick"/> </div> </template> <script> export default { name: "Child1", data () { return{ childValue:"这是子组件的数据" } }, // 接受传入的值 props:{ inputName:String, required:true }, methods:{ childclick(){ this.$emit('childByValue',this.childValue) }, }, } </script> <style scoped> </style>