作者:李妙妙_minioniu_173 | 来源:互联网 | 2023-09-18 11:39
我在一个js
文件中有两个组件,文件以const EventBus = new Vue();
开头
我想从第一个组件到第二个组件发送两个字符串'username'和'password',但是我做不到。我哪里错了?
第一:
Vue.component('log-reg-modal',{
data: () => ({
username: "",password: "",}),watch: {
username: function(){
EventBus.$emit('changed_username',this.username);
},password: function(){
EventBus.$emit('changed_password',this.password);
},}
});
第二:
new Vue({
el: '#app',vuetify: new Vuetify(),data: () => ({
username: "",methods: {
register : function (event) {
EventBus.$on('changed_username',this.username);
EventBus.$on('changed_password',this.password);
}
}
});
您将需要在EventBus.$on
生命周期方法中使用created
来“注册”接收事件。
您还可以跳过EventBus
,而只使用“内置”事件处理程序。
使用事件总线:
const EventBus = new Vue();
const LogRegModal = {
template: `
`,data: () => ({ username: "",password: "" }),watch: {
username: function() { EventBus.$emit("changed_username",this.username) },password: function() { EventBus.$emit("changed_password",this.password) },}
};
new Vue({
el: "#app",components: { LogRegModal },created() {
EventBus.$on("changed_username",val => this.username = val);
EventBus.$on("changed_password",val => this.password = val);
}
});
These values were received from the EventBus:
- Username: {{username}}
- Password: {{password}}
使用“内置” this.$emit(...,...)
:
const LogRegModal = {
template: `
`,watch: {
username: function() { this.$emit("changed_username",password: function() { this.$emit("changed_password",methods: {
handleUsernameChange(val) { this.username = val },handlePasswordChange(val) { this.password = val }
},});
code {
color: red;
}
p {
margin-bottom: 2px;
}
.second-p {
margin-top: 0px;
}
@changed_username="handleUsernameChange"
@changed_password="handlePasswordChange"
> These values were received via this.$emit
as 'props' on our component using v-on:event_name
(using @event_name
is shorthand for v-on:event_name
):
- Username: {{username}}
- Password: {{password}}
,
- EventBus。$ on中指示的处理程序应该是函数,而不是自我支持。
- 在开始使用 log-reg-modal 组件之前,您是否调用过 register 方法?
,
EventBus.$on
方法应根据Vue生命周期放在created()
函数中
created (){
EventBus.$on('changed_username',(data) => {
this.username = data;
});
EventBus.$on('changed_password',(data) => {
this.password = data;
});
}