Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Header and footer component in Vue.js

Tags:

vue.js

vuejs2

I am learning Vue.js, I am not using cli for Vue.js installation, I just downloaded Vue.js file and trying to learn it.

My issue is to externalize components like header.vue and footer.vue and add them to main component.

I used Vue.component('MyHeader', require('./components/Header.vue')); to load component but I was getting error like "Uncaught ReferenceError: require is not defined".

To resolve this error I downloaded require.js file from here but I am still unable to load component files.

Folder Structure

enter image description here

index.html

<!DOCTYPE html>
<html>
<head>
    <title>this is example of header and footer</title>
</head>
<body>

<div id='root'>
   <testcomponent></testcomponent>
   <MyHeader></MyHeader>
   <div>I am Content</div>
   <MyFooter></MyFooter>
</div>


<!-- we need this two files for vue js -->
<script type="text/javascript" src="vue.js"></script>
<script type="text/javascript" src="require.js"></script>
<!-- End of we need this two files for vue js -->
<script type="text/javascript" src="indexController.js"></script>
</body>
</html>

indexController.js

//rout file for vue js

Vue.component("testcomponent",{
    template:'<p>I am Test Component</p>'
});

Vue.component('MyHeader', require('./components/Header.vue'));
Vue.component('MyFooter', require('./components/Footer.vue'));

//import MyHeader from './components/Header.vue'
//import MyFooter from './components/Footer.vue'

var app = new Vue({
    el: "#root",
    components: {
        MyHeader,
        MyFooter
    },
    data: {
        
    },
    methods:{

    }

});

Header.vue

<template>
    <h1>I am Header</h1>
</template>

Footer.vue

<template>
    <h1>I am Footer</h1>
</template>
like image 558
Juned Ansari Avatar asked Mar 07 '23 19:03

Juned Ansari


1 Answers

Single file component (.vue)

You need vue-loader to convert .vue files to normal js format. If you will read the documentation at https://v2.vuejs.org/v2/guide/single-file-components.html, you basically need to use webpack or browserify to use .vue files extensions.

like image 174
Dencio Avatar answered Mar 25 '23 08:03

Dencio