Vue父组件向子组件传值的方法有以下几种:
示例:
- <template>
- <div>
- <child-component :message="parentMessage">child-component>
- div>
- template>
-
- <script>
- import ChildComponent from './ChildComponent.vue';
-
- export default {
- components: {
- ChildComponent
- },
- data() {
- return {
- parentMessage: 'Hello from parent'
- };
- }
- }
- script>
-
- <template>
- <div>
- <p>{{ message }}p>
- div>
- template>
-
- <script>
- export default {
- props: ['message']
- }
- script>
示例:
- <template>
- <div>
- <child-component @custom-event="handleCustomEvent">child-component>
- div>
- template>
-
- <script>
- import ChildComponent from './ChildComponent.vue';
-
- export default {
- components: {
- ChildComponent
- },
- methods: {
- handleCustomEvent(data) {
- console.log(data); // 子组件传递的数据
- }
- }
- }
- script>
-
- <template>
- <div>
- <button @click="handleClick">触发事件button>
- div>
- template>
-
- <script>
- export default {
- methods: {
- handleClick() {
- this.$emit('custom-event', 'Hello from child');
- }
- }
- }
- script>
这两种方法可以根据具体情况选择使用。使用Props可以在父子组件之间进行单向数据流的传递,适用于父组件向子组件传递初始值或实现一些静态数据的展示。而使用$emit自定义事件可以实现父子组件之间的双向通信,适用于需要响应用户交互行为的场景。
以上示例中,第一种方法通过props将父组件的parentMessage属性传递给子组件,并在子组件中显示该属性的值。第二种方法是在子组件中点击按钮时,通过$emit方法触发了一个自定义事件,并传递了字符串参数,父组件监听此事件并获取到子组件传递的数据。