Trekdrop
Trekdrop

Reputation: 495

Vue one or multiple instances?

I'm quite new to Vue (in combination with Laravel). I'm not sure what's the best vue (file) structure.

For example: I have a vue chat application and a sidebar that slides out. At this moment I have made one vue instance (at the #app element). All the code is now in this one vue instance. How should I seperate the data and code in the instance for my chatapp and sidebar?

 Vue.component('chat-message', require('./components/ChatMessage.vue'));
 Vue.component('chat-log', require('./components/ChatLog.vue'));
 Vue.component('chat-composer', require('./components/ChatComposer.vue'));

    new Vue({
        el: "#app",
        data: {


**//Data for the chatapp**

            messages : [],

**//Data for the sidebar**

            showSidebar: false
        },

**//Code for the chatapp**

        methods:{
            addMessage(message) {
                this.messages.push(message);
                axios.post('messages', message)
            }
        },
        created() {
            axios.get('messages').then(response => {
                this.messages = response.data;
        });

            Echo.join('chatroom')
                .listen('MessagePosted', (e) =>{
                this.messages.push({
                message: e.message.message,
                user: e.user,
            })
        });
        }
    });

I prefere to seperate this code to two seperate files (especially the methods and other code for the chatapp, e.g. chatroom.vue and sidebar.vue) and only load a clean vue instance e.g:

//Import components...
...
...
    new Vue({
        el: "#app"
    });

. Can I put this code into components? And how would this look like?

Thanks.

Upvotes: 2

Views: 1058

Answers (1)

shrpne
shrpne

Reputation: 428

You are right, you can and should separate it into two different components.

chatroom.vue

import ChatMessage from './components/ChatMessage.vue';
import ChatLog from './components/ChatLog.vue';
import ChatComposer from './components/ChatComposer.vue';

export default {
    components: {
        ChatMessage,
        ChatLog,
        ChatComposer,
    },
    data: {
        // Data for the chatapp
        messages : [],
    },
    // Code for the chatapp
    methods:{
        addMessage(message) {}
    },
    created() {}
}

sidebar.vue

export default {
    data: {
        // Data for the sidebar
        showSidebar: false,
    },
    // Code for the sidebar
}

app.js

import ChatRoom from './chatroom.vue';
import SideBar from './sidebar.vue';

new Vue({
    el: "#app",
    components: {
        ChatRoom,
        SideBar,
    },
});

Upvotes: 2

Related Questions