vue-cli创建项目,直接上码————
1-4父传字,5-8子传父
子组件
<template> <div id="app"> <p>子组件</p> <p>子组件:{{msg2}}</p> <p>接收父组件传值{{gozi}}</p> <!-- ⑤.子组件定义事件触发(@ 是 v-on简写) --> <button @click="gofu">传给父组件</button> </div> </template> <script> export default { name: ‘Child‘, data () { return { msg2: 50, msg3: ‘子组件传给父组件--30‘ } }, // ④.子组件通过props属性接收父组件传过来的值,Number为判断传值的类型 // 注:并且这是单向数据流,即当父组件的值改变时,传到子组件的值也会改变,反过来不行 props: { gozi: Number }, methods: { gofu () { // ⑥.通过$emit方法传数据给父组件 // gofus是组件名,父组件要用gefus方法接收传值,this.msg3是传给父组件的数据 this.$emit(‘gofus‘, this.msg3) } } } </script>
父组件
<template> <div id="app"> <p>父组件</p> <p>父组件:{{msg}}</p> <!-- ③.引用Child组件 用v-bind(简写 :)绑定子组件并将下面data内msg的值传到子组件--> <!-- ⑦. gofus是子组件提交的事件,getzi是父组件定义方法 --> <Child :gozi="msg" @gofus="getzi"></Child> </div> </template> <script> // ①.引入子组件 import Child from ‘./zi‘ export default { name: ‘App‘, data () { return { msg: 6 } }, // ②.注册组件 components: { Child }, methods: { // ⑧.得到子组件传过来的值 getzi (event) { console.log(event) } } } </script> <style> #app { font-family: ‘Avenir‘, Helvetica, Arial, sans-serif; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; text-align: center; color: #2c3e50; margin-top: 60px; } </style>
最后,拜拜~~记得推荐
原文:https://www.cnblogs.com/wangxiaomo/p/12587293.html