vue组件传值的方式 - 果核剥壳

props传值
1、props的概念

props(属性)是Vue组件中的一个核心概念,它用于在父组件和子组件之间传递数据,父组件通过props向子组件传递数据,子组件通过props接收并使用这些数据。

vue组件传值的方式
2、使用props传递数据

在父组件中,我们可以通过在子组件标签上添加属性来传递数据。

<!-父组件 -->
<template>
<div>
<child-component :message="parentMessage"></child-component>
</div>
</template>
<script>
import ChildComponent from './ChildComponent.vue';
export default {
components: {
ChildComponent
},
data() {
return {
parentMessage: '来自父组件的信息'
};
}
};
</script>
在子组件中,我们可以通过props选项来定义需要接收的数据。

vue组件传值的方式
<!-子组件 -->
<template>
<div>
{{ message }}
</div>
</template>
<script>
export default {
props: ['message']
};
</script>
自定义事件传值
1、customEvent的概念

Vue提供了一种自定义事件机制,允许我们在父子组件之间进行通信,我们可以在子组件中触发一个自定义事件,然后在父组件中监听这个事件并处理相应的逻辑。

2、在子组件中触发自定义事件

在子组件中,我们可以使用$emit方法来触发一个自定义事件。

<!-子组件 -->
<template>
<button @click="handleClick">点击我</button>
</template>
<script>
export default {
methods: {
handleClick() {
this.$emit('custom-event');
}
}
};
</script>
3、在父组件中监听自定义事件并处理逻辑

在父组件中,我们可以使用v-on指令来监听子组件触发的自定义事件,我们需要使用.native修饰符来告诉Vue这是一个原生事件,这样我们才能在事件处理函数中访问到相关的DOM元素。

<!-父组件 -->
<template>
<div>
<child-component @custom-event="handleCustomEvent"></child-component>
</div>
</template>
<script>
import ChildComponent from './ChildComponent.vue';
export default {
components: {
ChildComponent
},
methods: {
handleCustomEvent(payload) {
console.log('收到子组件的自定义事件', payload); // '来自子组件的信息';
}
}
};
</script>
$refs传值(适用于插槽)与作用域插槽(v-slot)结合使用时,我们可以使用$refs来访问子组件的实例,从而实现数据的双向绑定,但这种方式仅适用于插槽,不适用于普通的props和自定义事件,以下是一个简单的示例
Markup
<!-Parent.vue -->
<template>
<div>
<child-component>我是插槽内容</child-component> <!-这里使用了作用域插槽 -->
</div>
</template>
<script>// ... */</script>'use strict';const ChildComponent = Vue.extend({});export default new ChildComponent();```

如果您喜欢本站,点击这儿不花一分钱捐赠本站

这些信息可能会帮助到你: 下载帮助 | 报毒说明 | 进站必看

修改版本安卓软件,加群提示为修改者自留,非本站信息,注意鉴别

(0)
上一篇 2024年1月12日 上午10:03
下一篇 2024年1月12日 上午10:07

相关推荐

发表回复

评论问题之前,点击我,能帮你解决大部分问题

您的电子邮箱地址不会被公开。 必填项已用*标注