javascript - 在两个兄弟组件之间传递一个数组
问题描述
所以我有“主页”组件,用户可以在那里创建二维码。我有一种方法可以创建这些 QR 项的数组。现在我需要将此数组传递给其他组件,它是兄弟组件,而不是子父/父子关系。
我试图创建 eventBus,但进展不顺利。
应用程序.vue
<template>
<div class="container-fluid">
<app-header></app-header>
<div class="row">
<div class="col-sm-12">
<router-view></router-view>
</div>
</div>
</div>
</template>
<script>
import { eventBus } from './main';
import Header from './components/Header.vue';
export default {
data() {
return {
urls: []
}
},
created() {
eventBus.$on('updateUrls', (data) => {
this.urls.push(this.data);
})
},
components: {
'app-header': Header
}
}
</script>
<style>
</style>
主页.vue
<template>
<div>
<h2>Welcome to QR</h2>
<p>Generate qr codes on your own website</p>
<hr>
<div class="form-group">
<label>Your website address:</label>
<input type="text" class="form-control" v-model="address">
</div>
<a :href="url" target="_blank" class="btn btn-primary" :disabled="!address">Generate</a>
<button class="btn btn-primary" :disabled="!address" @click="saveData">Save</button>
<button class="btn btn-secondary" @click="clearInput" :disabled="!address">Clear</button>
</div>
</template>
<script>
import axios from 'axios';
import { eventBus } from '../main';
export default {
data() {
return {
address: '',
prefix: `https://www.qrtag.net/api/qr_4.png?url=`,
}
},
computed: {
url() {
const url = this.prefix + this.address;
return url;
}
},
methods: {
clearInput() {
this.address = ''
},
saveData() {
const data = {
url: this.url,
date: new Date()
}
eventBus.$emit('updateUrls', this.data);
},
}
}
</script>
历史.vue
<template>
<div>
<router-link tag="a" class="nav-link" to="/dashboard">Generate another QR</router-link>
<p :urls="urls" v-for="link in urls">{{ link.url }}</p>
</div>
</template>
<script>
import { eventBus } from '../main';
export default {
props: ["urls"],
data() {
return {
}
}
}
</script>
main.js
export const eventBus = new Vue();
解决方案
尝试以下代码段:
Vue.component('home',{
template: `<div>
<h2>Home Component</h2>
<button @click="sendQrCode">Check</button>
</div>`,
methods:{
sendQrCode:function(){
this.$root.$emit("codeSent",["code1","code2","code3"]);
}
}
});
Vue.component('history',{
template: `<div>
<h2>History Component</h2>
{{ codes }}
</div>`,
data:function(){
return {
codes:null
}
},
created(){
let that = this;
this.$root.$on("codeSent",(payload)=>{
that.codes = payload;
})
}
});
new Vue({
el:"#app"
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.min.js"></script>
<html>
<body>
<div id="app">
<home></home>
<hr />
<history></history>
</div>
</body>
</html>
推荐阅读
- java - 如何打开像谷歌应用广告这样的应用安装页面
- php - 我不能在我的 $_SESSION['car'] 数组中添加多个对象
- excel - 如何在 Excel 单元格中使用 OR 和 AND 执行 IF?
- r - 如何通过用户选择对数据进行子集化以在 R 闪亮的应用程序中绘图
- jqassistant - 如何使用 jqassistant 检测/解决超级方法调用
- python - 任何统计测试来了解数据 - 更高的价格是否会带来更好的质量?
- python - ValueError: `generator` 产生了一个形状为 (2, 200, 200, 3) 的元素,其中需要一个形状为 (4, 200, 200, 3) 的元素
- javascript - 如何根据 id 隔离对象?
- typescript - 打字稿“对象可能是‘空’”误报
- python - Pyspark:我可以从数据块中读取来自谷歌云的文件吗?