因Vue组件之间值不能共享,所以需要通过内部指定属性进行传递。(PS:驼峰命名,标签引用是要用-隔开)
一,父类组件向子类组件传值
<body> <div id="app"> <user-Parent-Comp></user-Parent-Comp> </div> </body> <script> var vm = new Vue({ el: '#app', components: { 'userParentComp': { template: '<h1>I am a parent component.---{{parentVal}}<br/><userChildComp :childVal="fromParentVal"/></h1>', data() { return { parentVal: 'I am the value of a parent class. ', fromParentVal: 'I am a value from the parent class. ' } }, components: { 'userChildComp': { props: ['childVal'], template: '<p>I am a child component.---{{childVal}} </p>' } } } } }) </script>运行效果:
二、子组件传值到父组件。
<body> <div id="app"> <user-Parent-Comp></user-Parent-Comp> </div> </body> <script> var vm = new Vue({ el: '#app', components: { 'userParentComp': { template: '<h1>I am a parent component.---{{fromChildVal}} <userChildComp @upParamsFun="fillValFun"></userChildComp></h1>', data() { return { fromChildVal: 'default parentVal' } }, methods: { fillValFun(upVal) { this.fromChildVal = upVal; } }, components: { 'userChildComp': { data() { return { fromChildVal: 'I am a value from the child class. ' } }, template: '<p v-on:click="userFun">I am a child component.点击我就发送数据到父组件 </p>', methods: { userFun() { this.$emit('upParamsFun', 'I am a value from the child class.'); } } } } } } }) </script>运行效果:
步骤一:点击前
步骤二:点击后