将计算值从组件传递给父级

将计算值从组件传递给父级

本文介绍了VueJS 将计算值从组件传递给父级的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我制作了一个 VueJS 组件,它操作一些 元素.此 UI 的结果是用户选择了一个值.

I've made a VueJS component that operates some <select> elements. The result of this UI is that the user selects a value.

我在组件的 computed 中有一个函数,用于在屏幕上显示用户选择的值.

I have a function in the compoent's computed for showing the user's selected value on screen.

如何将此值传递回父 VueJS 东西?

How do I pass this value back to the parent VueJS thingy?

$emit 似乎是这样,但我没有看到我有一个事件.

It seems to be something to so with $emit but I don't see that I have an event.

我已经按照建议提出了一个这里,但现在没有发生.

I've tied to raise one as suggested here, but nowt happens.

在组件中:

        computed: {
            selectedCode: function () {
                var selected = '(No code selected.)';
                if (this.category) { selected = this.category; }
                if (this.code) { selected = this.code; }

                this.$emit('selectedCode', selected);

                return selected;
            },

在父 Vue 应用中:

In the parent Vue app:

<code-selector v-bind:code="code" v-on:selectedCode="codeSelect"></sic-selector>

                methods:
                {
                    selectedCode: function (z) {
                        console.log(z);
                    },

推荐答案

这里的问题主要是因为发出了一个驼峰式事件名称.因此,正如文档中所述:>

如果发出驼峰式事件名称:

The issue here is mainly because of emitting a camelCased event name. So, as mentioned in the docs:


If emitting a camelCased event name:

听 kebab-cased 版本没有效果:

this.$emit('myEvent')

Listening to the kebab-cased version will have no effect:

与组件和道具不同,事件名称永远不会在 JavaScript 中用作变量或属性名称,因此没有理由使用驼峰式大小写或 PascalCase.此外,DOM 模板中的 v-on 事件侦听器将自动转换为小写(由于 HTML 不区分大小写),因此 v-on:myEvent 将变为 v-on:myevent – 使 myEvent 无法监听.

<!-- Won't work --><my-component v-on:my-event="doSomething"></my-component>

出于这些原因,我们建议您始终使用 kebab-case 作为事件名称.

Unlike components and props, event names will never be used as variable or property names in JavaScript, so there’s no reason to use camelCase or PascalCase. Additionally, v-on event listeners inside DOM templates will be automatically transformed to lowercase (due to HTML’s case-insensitivity), so v-on:myEvent would become v-on:myevent – making myEvent impossible to listen to.

所以,只需发出一个 kebab-case 事件名称,例如:

For these reasons, we recommend you always use kebab-case for event names.

So, just emit a kebab-case event name like:

然后你就可以轻松地听:

this.$emit('selected-code', selected);

and then you can easily listen to it like:

这是一个工作演示:



注意:请注意您在帖子中分享的问题的答案中分享的演示我可以从子组件到父组件获取计算数据吗?codepen,有一个简单的发射事件名称,如:

Note: Please note that the demo shared in the answer in the question that you have shared in your post Can I get computed data from child component to parent component? on codepen, has a simple emitted event name like:

this.$emit('update', e.target.valueAsNumber)

因此代码在该演示中工作.

Thus the code is working in that demo.

这篇关于VueJS 将计算值从组件传递给父级的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 14:23