gpt4 book ai didi

javascript - Vue.js 在一个组件内的另一个组件中使用变量

转载 作者:行者123 更新时间:2023-11-27 23:17:08 25 4
gpt4 key购买 nike

我有一张员工表。每个员工都有一个 Angular 色,我正在尝试使用单选按钮(例如单选按钮管理员或 super 管理员)来过滤该 Angular 色。

如何在另一个组件中使用一个组件内的变量?现在我有这个:

   <template id="searchemployees">
<div class="form-group">
<label class="col-md-2 control-label">Filter</label>

<div class="col-md-10">
<div class="radio radio-primary">
<label>
<input type="radio" name="intern" id="intern" value="intern" v-model="selectedrole"/>
Toon alles
</label>
</div>
<div class="radio radio-primary">
<label>
<input type="radio" name="employee" id="employee" value="employee" v-model="selectedrole">
Stagiaire
</label>
</div>
</div>
</div>
</template>

<template id="employees">
<table class="table">
<thead>
<tr>
<th>Logo</th>
<th>Bedrijfsnaam</th>
<th>Plaats</th>
</tr>
</thead>
<tbody>
<tr class="table-row-link" data-href="" v-for="employee in list | role selectedrole">
<td><img class="img-circle-company" src=""/></td>
<td>@{{ employee.role.RoleName }}</td>
<td>@{{ employee.LastName }}</td>
</tr>
</tbody>
</table>
</template>

<script>
Vue.config.debug = true;

Vue.filter('role',function(value,role)
{
if(!role || 0 === role.length)
{
return value;
}
return value.filter(function(item) {
return item.role.RoleName == role
});
});

Vue.component('searchemployees', {
template: '#searchemployees'
});

Vue.component('employees', {
template: '#employees',
props:['list'],
created() {
this.list = JSON.parse(this.list);
}
});

new Vue({
el: 'body'
});
</script>

在我的#searchemployees中,它采用正确选择的 Angular 色。但如何在 #employees 中将它用于我的过滤器?

谢谢

最佳答案

您应该能够通过分派(dispatch)事件将属性从组件向上发送到根/全局 Vue 实例。分派(dispatch)事件意味着您正在向 Vue 树中组件的父组件发送一条包含属性的消息。您可以使用以下语法分派(dispatch)事件:

this.$dispatch('event-name', this.list);

这表示,将 ID 为 event-name 且包含属性 this.list 的事件发送到组件的父组件。

如果您的组件的父组件正在监听 ID 为 event-name 的确切消息,则该组件的父组件只能接收此分派(dispatch)属性。您可以使用以下代码监听父组件中的事件(这位于父组件中):

events: {
'event-name': function(property) {
console.log("Property from child component" + property);
}
}

总的来说,您的代码应该如下所示:

Vue.component('employees', {
template: '#employees',
props:['list'],
created() {
this.list = JSON.parse(this.list);
this.$dispatch('send-list', this.list);
}
});

new Vue({
el: 'body',
data: {
rootlist: {}
},
events: {
'send-list': function(property) {
this.rootlist = property;
console.log("Property from child component" + property);
}
}
});

这将使您的所有 [list] 数据在根 Vue 实例中可用。如果您想将其发送到所有组件,可以在 send 中创建一个广播事件 this.$broadcast('send-list-down', this.list); -list 函数。 $broadcast$dispatch 执行完全相同的操作,但它将数据沿着 Vue 树向下发送,而不是向上发送。只需确保在组件中为 send-list-down 事件创建事件监听器即可。

关于javascript - Vue.js 在一个组件内的另一个组件中使用变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35727169/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com