我正在测试VueJs用于测试目的,用户将发送一些消息,消息将通过组件呈现给主页。
这里我使用了三个组件..但是当我发送消息时,我看到以下消息......控制台:
[Vue警告]:财产或方法"消息"没有定义 实例,但在渲染期间引用。
[Vue警告]:属性或方法" addMessage"没有定义 实例,但在渲染期间引用。确保声明被动 数据选项中的数据属性。
这是刀片页面:
<html>
<head>
<meta charset="utf-8">
<title>Chatroom</title>
<link rel="stylesheet" href="css/app.css">
</head>
<body>
<div id="app">
<h1>Chatroom</h1>
<chat-log :messages="messages"></chat-log>
<chat-composer v-on:messagesent="addMessage"></chat-composer>
</div>
<script src="js/app.js" charset="utf-8"></script>
</body>
</html>
以下是ChatMessage.vue
个组件:
<template lang="html">
<div class="chat-message">
<p>{{ message.message }}</p>
<small>{{ message.user }}</small>
</div>
</template>
<script>
export default {
props: ['message']
}
</script>
<style lang="css">
.chat-message {
padding: 1rem;
}
.chat-message > p {
margin-bottom: .5rem;
}
ChatLog.vue
<template lang="html">
<div class="chat-log">
<chat-message v-for="message in messages" :message="message"></chat-message>
</div>
</template>
<script>
export default {
props: ['messages']
}
</script>
<style lang="css">
.chat-log .chat-message:nth-child(even) {
background-color: #ccc;
}
ChatComposer.vue
<template lang="html">
<div class="chat-composer">
<input type="text" placeholder="Start typing your message..." v-model="messageText" @keyup.enter="sendMessage">
<button class="btn btn-primary" @click="sendMessage">Send</button>
</div>
</template>
<script>
export default {
data() {
return {
messageText: ''
}
},
methods: {
sendMessage() {
this.$emit('messagesent', {
message: this.messageText,
user: "John Doe"
});
this.messageText = '';
}
}
}
</script>
<style lang="css">
.chat-composer {
display: flex;
}
.chat-composer input {
flex: 1 auto;
}
.chat-composer button {
border-radius: 0;
}
</style>
app.js(主要vue js文件)
require('./bootstrap');
Vue.component('example', require('./components/Example.vue'));
Vue.component('chat-message', require('./components/ChatMessage.vue'));
Vue.component('chat-log', require('./components/ChatLog.vue'));
Vue.component('chat-composer', require('./components/ChatComposer.vue'));
const app = new Vue({
el: '#app',
data: {
messages: [
{
message: 'Hey!',
user: "John Doe"
},
{
message: 'Hello!',
user: "Jane Doe"
}
]
},
methods: {
addMessage(message) {
// Add to existing messages
this.messages.push(message);
// Persist to the database etc
}
}
});
答案 0 :(得分:1)
由于主html页面中引用了chat-log
和chat-composer
组件,因此发送给它们的数据必须位于主Vue实例中。
messages
以及您希望成为侦听器的addMessage
方法将在发送消息时通知主实例必须位于主vue js实例内(根)
new Vue({
//your code
data:{
messages:[]//populate it with some data
},
methods:{
addMessage(message){
//this will get called when chat composer calls sendMessage
}
}
})