作者:文人博客 | 来源:互联网 | 2023-09-05 05:00
父子组件
<html><head><meta charset&#61;"UTF-8"><title>title><script type&#61;"text/Javascript" src&#61;"js/vue.js" >script>head><body><div id&#61;"box"><aaa>aaa>div>body><script>var vm &#61; new Vue({el: &#39;#box&#39;,data: {},components: {&#39;aaa&#39;: {template: &#39;我是aaa组件
&#39;,components: {&#39;bbb&#39;: {template: &#39;我是bbb组件
&#39;}}}}});script>
html>

子组件使用父组件数据
vue默认情况下&#xff0c;子组件没法访问父组件数据的&#xff0c;我们需要借助组件的props属性来绑定数据&#xff0c;使用props时注意html转js命名转换是使用驼峰转换的。
<html><head><meta charset&#61;"UTF-8"><title>title><script type&#61;"text/Javascript" src&#61;"js/vue.js" >script><style>style>head><body><div id&#61;"box"><aaa>aaa>div><template id&#61;"aaa"><span>我是父级 -> {{msg}}span><bbb &#64;child-msg&#61;"get">bbb>template><template id&#61;"bbb"><h3>子组件 ---> h3><input type&#61;"button" value&#61;"send" &#64;click&#61;"send" />template>body><script>var vm &#61; new Vue({el: &#39;#box&#39;,data:{},components:{&#39;aaa&#39;: {data() {return {msg: 111,msg2: &#39;我是父组件的数据&#39;}},template: &#39;#aaa&#39;,methods: {get(msg) {this.msg &#61; msg;}},components: {&#39;bbb&#39;: {data() {return {a: &#39;我是子组件的数据&#39;}},template: &#39;#bbb&#39;,methods: {send() {alert("子组件点击了");this.$emit(&#39;child-msg&#39;,this.a);}}}}}}});script>
html>
点击【子组件】中的按钮&#xff0c;然后调用【子组件】触发函数$emit
到【父组件】方法中&#xff0c;以此方式将【子组件数据】传递到【父组件】中。

