mos*_*mos 3 javascript events vue.js
在带有 vue.js 2 的项目中:
我有一个位于 .vue 文件中的组件,该文件表示元素列表。另外,我有一个侧边栏是这个列表的摘要。这个侧边栏是 .vue 文件中的另一个组件。
那么,我如何保持它们之间的通信,例如,如果我从列表中删除了一个元素,反映了侧边栏中声明的 var 的变化,即元素总数?举例说明:
SideBar.vue
<template>
...
<span></span> ===> here I need total of elements listed in ListElements.vue
...
<template>
Run Code Online (Sandbox Code Playgroud)
列表元素.vue
<template>
...
@click="deleteEntry"
...
<template>
<script>
methods: {
deleteEntry(entry) {
//here I need to notify to SideBar.vue in order to update the total of elements in the this.entries list.
let index = this.entries.indexOf(entry);
if (window.confirm('Are you sure you want to delete this time entry?')) {
this.entries.splice(index, 1);
}
}
</script>
Run Code Online (Sandbox Code Playgroud)
好的,我已经创建了一个简单的例子来说明它是如何工作的。您的总线需要是全局的,以便所有Vue组件都可以访问它,这仅意味着将其放置在所有其他组件和视图模型之外:
var bus = new Vue({});
var vm = new Vue({
// Main view model has access to bus
el: '#app'
});
Run Code Online (Sandbox Code Playgroud)
然后你只需要在总线上的某个事件上发出事件并在另一个组件中捕获它:
组件一在 keyup 上向总线发出一条消息:
Vue.component('component-one', {
template: '<div>Enter a message: <input v-model="msg" v-on:keyup="updateMessage"> </div>',
methods: {
updateMessage() {
bus.$emit('msg', this.msg);
}
},
data() {
return {
msg: ""
}
}
});
Run Code Online (Sandbox Code Playgroud)
组件二监听消息:
Vue.component('component-two', {
template: "<div><b>Component one says: {{ msg }}</b></div>",
created() {
bus.$on('msg', (msg) => {
this.msg = msg;
});
},
data() {
return {
msg: ""
}
}
});
Run Code Online (Sandbox Code Playgroud)
这是小提琴:https : //jsfiddle.net/v7o6d2vL/
为了让您的单页组件访问总线,您只需要确保您的总线在全局范围内,您可以使用window:
window.bus = new Vue({});
Run Code Online (Sandbox Code Playgroud)
然后您可以像往常一样在组件内部使用bus.$emit()和bus.$on()
| 归档时间: |
|
| 查看次数: |
1096 次 |
| 最近记录: |