javascript - vue中如何声明变量而不返回它?

标签 javascript html vue.js

我试图通过事件将函数发送到父组件,但是当我尝试声明将函数存储在“data(){return: }”内的变量时,函数会在变量接收它。我需要找到一个地方来声明变量而不自动执行其中的函数。

//child
export default: {
    data() {
        return {
            submit_method: { type: Function }
        }
    },
    methods: {
        open(type) {
            if(type == 'newFolder') {
                this.$refs.newFolder.show()
                this.submit_method = this.exportFile()
            } else {
                this.$refs.olderOmbudsman.show()
            }
        },
        exportFile() {
            if ( this.doc.origin.id != null ) {
                window.open(`${window.globals.API_SERVER}/ombudsman/doc/?page=${this.doc.page}&origin=${this.doc.origin.id}`, '_target')
            }else{
                alert("Choose the origin!");
            }
        }
    },
    activated() {
        this.$emit('export-ombudsman', submit_method)
    }
}

最佳答案

我注意到的第一个奇怪之处是:

return {
    submit_method: { type: Function }
}

Props 支持类型,data 不支持。您在这里所做的就是将对象 {type: Function} 分配给 submit_method

然后是这样的:

this.submit_method = this.exportFile()

这是立即调用该方法。我想你的意思是这样的:

this.submit_method = this.exportFile

然后我们得到了这个:

this.$emit('export-ombudsman', submit_method)

在模板中,您需要删除 this. 才能访问成员,但在 JavaScript 中无法执行此操作。这需要是:

this.$emit('export-ombudsman', this.submit_method)

所有这些都假设 submit_method 是动态的。如果不是,那么您可以直接传递 exportFile :

this.$emit('export-ombudsman', this.exportFile)

即使您确实需要动态函数,也不需要在 data 中声明 submit_method ,除非您需要它是响应式的。即使它不在 data 中,您仍然可以将其保存到 this

关于javascript - vue中如何声明变量而不返回它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56892371/

相关文章:

javascript - 从 AngularJS 中的 location.search 中删除项目

javascript - jquery多次clone和appendTo性能

javascript - 在一页中显示多个地理图表?

javascript - React 的背景位置内联样式

javascript - Angularjs:根据事件选项卡加载选项卡,但阻止在访问的选项卡上呈现

javascript - 无法在 Angular 4 中显示单个 JSON 对象属性

php - 用替代颜色为表格着色

Vue.js - 将参数传递给子路由

vue.js - 如何将 BootstrapVue 中的 Prop 传递给路由器链接

javascript - 无法从子组件获取在父组件上执行的方法