当前位置: 代码迷 >> 综合 >> Vue父子组件相互传值
  详细解决方案

Vue父子组件相互传值

热度:15   发布时间:2023-09-06 13:59:40.0
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>父子组件相互传值</title><!--<script src="vue.js"></script>--><script type="text/javascript" src="https://unpkg.com/vue"></script>
</head>
<body>
<div id="app"><parent-component></parent-component>
</div>
<script>//子组件Vue.component('childComponent', {template: '<div style="height:100px; width:150px; background-color: red;margin:2px;">' +'{{hello}}' +'<button @click="changeParent">子级</button>' +'</div>',props: ['hello'],  //从父组件取值methods: {changeParent: function () {this.$emit('myEventInvoke', '子组件的值');}}});//父组件Vue.component('parentComponent', {template: '<div style="height:250px; width:250px; background-color:green;">' +'<button @click="change">父级</button>' +'{{hello}}' +'<childComponent :hello="hello" @myEventInvoke="myChangeText"></childComponent>' +'</div>',data: function () {return {hello: '父组件Hello'}},methods: {change: function () {this.hello = '父级改变了hello';},myChangeText: function (data) {this.hello = '第二次改变'}}});new Vue({el: '#app'});
</script>
</body>
</html>
  相关解决方案