简体   繁体   English

Vue 2.0 - 如何将函数传递给子组件?

[英]Vue 2.0 - How passing function to child component?

I have one issue.我有一个问题。 I want to pass function link to the child component.我想将函数链接传递给子组件。 It's working but in HTML I get that code.它正在工作,但在 HTML 中我得到了该代码。 It's correct how improve it?对了怎么改善?

I have Vue instance我有 Vue 实例

app = new Vue({
    ... some code
    data: {
      onAppClose: null,
      onAppSend: null
    }
})

I want to add from global window any function.我想从全局窗口添加任何功能。 Or register function in Vue instance或者在 Vue 实例中注册函数

app.onSend = () => console.log('data')

And pass this function to child并将此功能传递给孩子

<div id="app">
        <dynamsoft-component v-if="displayComponent" 
            :docs="docs"
            :onAppSend="onSend"
            :onAppClose="onClose"
        ></dynamsoft-component>
    </div>

But I get this HTML template in console但是我在控制台中得到了这个 HTML 模板

<div id="app">
 <div onappsend="()=>{}" onappclose="function (data) {
    console.warn('dwdawad')
    console.log('data')
}"></div>
</div>

You example code is not making a lot of sense - do you want to add a listener not a div or pass a function to a child component?`您的示例代码没有多大意义 - 您是要添加侦听器而不是 div 还是将函数传递给子组件?`

I assume the latter.我假设后者。 Vue has custom events for that . Vue 对此有自定义事件

Parent template:父模板:

<div v-on:appsend="someMethod" v-on:appclose="someOtherMethod"></div>

Parent component methods:父组件方法:

methods: {
  someOtherMethod: function (data) {
    console.warn('dwdawad')
    console.log('data')
  },
  // ...
}

And then emit form the child:然后从孩子身上发出:

this.$emit('appclose', {id: 'whatever'} /*pass data here*/)

Edit:编辑:

I still don't see how those functions would end up directly in the template, but the real problem is: HTML is not case-sensitive.我仍然看不到这些函数将如何直接在模板中结束,但真正的问题是:HTML 不区分大小写。 so :onAppSend becomes :onappsend .所以:onAppSend变成:onappsend You have to use kebap-case: :on-app-send .你必须使用 kebap-case: :on-app-send Vue will convert it to onAppSend in the component. Vue 会将其转换为组件中的onAppSend

I have never used Vue.js before now..我以前从未使用过 Vue.js..
But having a look at the how to on their site, this seems to work但是看看他们网站上的操作方法,这似乎有效

In Vue style guide have recommendations about props naming https://v2.vuejs.org/v2/style-guide/#Prop-name-casing-strongly-recommended在 Vue 风格指南中有关于道具命名的建议https://v2.vuejs.org/v2/style-guide/#Prop-name-casing-strongly-recommended

 Vue.component('dynamsoft-component', { props: ['onAppSend'], template: '<button v-on:click="buttonclick">click me</button>', methods: { buttonclick(e){ // Check if onAppSend is defined. if(Boolean(this.onAppSend)){ this.onAppSend(); } } } }) new Vue({ el: '#app', methods: { onSend: function(){ console.log('child clicked'); } } });
 <script src="https://cdn.jsdelivr.net/npm/vue"></script> <div id="app"> <dynamsoft-component :on-app-send="onSend"></dynamsoft-component> </div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM