【发布时间】:2018-05-03 22:02:06
【问题描述】:
好的,所以我知道我不应该调用孩子的方法,而是传递它的道具。
我有(父母):
<template>
<div id="main">
<Header :title ="title"/>
<router-view/>
<LateralMenu/>
</div>
</template>
<script>
export default {
name: 'app'
data: function () {
return {
title: true
}
},
methods: {
hideTitle: function () {
this.title = false
console.log(this.title)
},
showTitle: function () {
this.title = true
console.log(this.title)
}
}
}
</script>
和(孩子):
<script>
export default {
name: 'Header',
props: ['title'],
created () {
console.log(this.title)
},
methods: {
}
}
</script>
第一个控制台日志(在父级内部)在每种方法上都正确打印,但子级中的第二个控制台日志始终保持真实。我是从:Pass data from parent to child component in vue.js
每次触发父级中的方法时,console.log需要打印在什么方法里面?
(这就是为什么我想进行方法调用的原因,最初,通过使用变量来代替,我们可能会省略流程中有价值的部分,例如优化和执行的“时间”!!)我们的代码。这里是关键词,不要对我大发雷霆,记住我正在学习。)
旧:
我浏览过网络,我知道有一百万种不同的答案 我的观点是最新版本的 vue 没有那些数以百万计的 答案有效。
要么所有内容都已弃用,要么只是不适用,但我需要一个 解决方案。
如何调用子方法?
我有 1 个组件 = 1 个文件设置。
DOM 在
<template>标签内声明 javascript 写在里面<script>标签。我要离开 vue-cli 脚手架了。我尝试过的最新方法是@emit(有时与@on 配对 有时不是)不起作用:
孩子:
<script> export default { name: 'Header', created () { this.$on('hideTitlefinal', this.hideTitlefinal) }, methods: { hideTitlefinal: function () { console.log('hideeeee') }, showTitlefinal: function () { console.log('shwowwww') } } } </script>父母:
<template> <div id="main"> <Header v-on:hideTitle="hideTitlefinal" v-on:showTitle="showTitlefinal"/> <router-view/> <LateralMenu/> </div> </template> <script> export default { methods: { hideTitle: function () { this.$emit('hideTitle') }, showTitle: function () { this.$emit('showTitle') } } } </script>控制台:
Uncaught TypeError: this.$emit is not a function at Object.showTitle (Main.vue?1785:74) at VueComponent.showTitle (LateralMenu.vue?c2ae:113) at boundFn (vue.esm.js?efeb:186) at invoker (vue.esm.js?efeb:1943) at HTMLDivElement.fn._withTask.fn._withTask (vue.esm.js?efeb:1778)
【问题讨论】:
-
你不调用孩子的函数,你传递道具。反应式框架的重点是对数据做出反应。也就是说,这在技术上是可行的,只是一个坏主意,这就是为什么你找不到任何关于如何实现这一点的文档。
-
好吧,我不明白传递道具是什么样子的,你能给我举个例子吗?
标签: vuejs2 call parent-child