javascript - Vue2Js:是否可以调用具有来自另一个组件的属性的方法?
问题描述
我有 3 个组件:组件 1 是顶部菜单,组件 2 是一种具有功能的库,组件 3 是主要代码。
理想情况下,我想在组件 1 中使用组件 2 中的方法和组件 3 中的属性。然后在组件 3 中使用组件 1。
// Component 1 Top Menu
Vue.component('component1', {
props: {
titleTest: {
type: String,
required: true
},
textTest: {
type: String,
required: true
}
},
template: `
<div>
<div :title="titleTest">{{ titleTest }}</div>
<div :data-test="textTest">{{ textTest }}</div>
<button id='test' type="submit" @click="bar">TestButton</button>
</div>
`,
created() {
console.log('Created1');
this.$root.$refs.component1 = this;
},
methods: {
//alertText should be passed from Component 3
bar: function(alertText) {
console.log(alertText);
this.$root.$refs.component2.foo(alertText);
}
}
});
// Component 2 Lib
Vue.component('component2', {
created() {
this.$root.$refs.component2 = this;
},
methods: {
foo: function(alertText) {
alert('this is component2.foo' + alertText);
}
}
});
// Component 3 Main Code
Vue.component('component3', {
template: `
<div>
<div>Some text</div>
<ul>
<li>List Item1</li>
<li>List Item2</li>
</ul>
<div>
<component1 ref="component1" :title-test="test1" :text-test="test2"></component1>
</div>
</div>
`,
data: function() {
return {
test1: 'testText1',
test2: 'testText2',
alertText: 'alertText'
};
},
created: function() {
}
});
new Vue({
el: '#plotlyExample',
});
我不确定这是否可能,尝试使用“发射”但没有奏效。
解决方案
当你调用时Vue.component('component2', {...})
,它只是告诉 Vue 关于命名组件,并且不会生成组件实例,因为它的使用方法component2
应该被渲染/安装。但我认为,你错误地使用component2
,同样,使用 mixins 或提供/拒绝或 vuex 会更好。
推荐阅读
- php - 如何在 PHP 字符串中回显 $_SESSION['username']?
- php - 使用带有流和参数的 php guzzle 进行 PUT
- google-colaboratory - 运行任何单元的 Google Colab 收到与 javascript 相关的错误
- reactjs - 如何在 AEM Maven 项目中使用 Adobe 的 React Web Component 工具
- ninject - 如何将 Ninject 绑定到 [Obsolete] 构造函数?
- python-3.x - Python pika - 发布到不存在的交换不会引发异常
- c - 警告:初始化从指针目标类型中丢弃“const”限定符 [-Wdiscarded-qualifiers]
- c# - 是否可以在 TextChangeEvent 中为 TextBox 设置焦点
- android - 如何在 Kotlin 中完全实现 Navigation Drawer 模板
- salesforce - 内连接两个没有关系的 SOQL 对象