去官网学习→Props | Vue.js
运行示例:
代码:App.vue
<template><img alt="Vue logo" src="./assets/logo.png"><h2>Vue Props数据传递</h2><h4>子组件中的数据:{{ content }}</h4><!-- 自定义事件 @onEvent getHandle方法 --><MyComponent @onEvent="getHandle"/></template><script>import MyComponent from "./components/MyComponent.vue"export default {name: 'App',data(){return{content:""}},components: {MyComponent},methods:{getHandle(data){// 获取到子组件的数据 data// alert(data);this.content = data;}}
}
</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>
代码:MyComponent.vue
<template><button @click="sendHandle">向父组件传递数据</button>
</template><script>export default {name:"MyComponent",data(){return{content:"子组件中的内容",numb:100}},methods:{sendHandle(){//$emit(event: string, ...args: any[])// .$emit 往父组件传递数据this.$emit("onEvent",[this.content,this.numb])}}}
</script><style scoped></style>