官术网_书友最值得收藏!

Loading modules without Webpack

Although Webpack helps us in more ways than simply loading a module, we can load a JavaScript module at this moment in time natively in the browser. It tends to perform worse than bundling tools (at the time of writing), but this may change over time.

To demonstrate this, let's head over to the terminal and make a simple counter with a project based on the simple template. This template effectively starts a new Vue project without any bundling tools:

# New Vue Project
vue init simple vue-modules

# Navigate to Directory
cd vue-modules

# Create App and Counter file
touch app.js
touch counter.js

We can then edit our index.html to add script files from type="module" this allows us to use the export/import syntax outlined before:

<!-- index.html -->
<!DOCTYPE html>
<html>
<head>
<title>Vue.js Modules - Counter</title>
<script src="https://unpkg.com/vue"></script>
</head>
<body>
<div id="app">
</div>
<script type="module" src="counter.js"></script>
<script type="module" src="app/app.js"></script>
</body>
</html>

Warning: Ensure that your browser is up to date so that the preceding code can run successfully.


Then, inside of our counter.js, we can export a new default object, which acts as a new Vue instance. It acts as a simple counter that allows us to either increment or decrements a value:

export default {
template: `
<div>
<h1>Counter: {{counter}}</h1>
<button @click="increment">Increment</button>
<button @click="decrement">Decrement</button>
</div>`,
data() {
return {
counter: 1
};
},
methods: {
increment() {
this.counter++;
},
decrement() {
this.counter--;
}
}
};

We can then import the counter.js file inside of app.js, thus demonstrating the ways we can import/export modules. To get our counter to display inside of our root Vue instance, we're registering the counter as a component inside this instance, and setting the template to <counter></counter>, the name of our component:

import Counter from './counter.js';

const app = new Vue({
el: '#app',
components: {
Counter
},
template: `<counter></counter>`
});

We'll look at this in more detail in future sections of the book, but all you need to know at this point is that it effectively acts as another Vue instance. When we register the component inside of our instance, we're only able to access this component from that instance.

Awesome! Here are the results of our module import/exports:

Vue.js Modules

In the next section, we'll take a deeper look at debugging our Vue applications, and the role Vue devtools plays in this.

主站蜘蛛池模板: 辽阳市| 班玛县| 江北区| 盐源县| 崇明县| 边坝县| 晋城| 潜山县| 太仆寺旗| 霞浦县| 永丰县| 稷山县| 墨江| 湖南省| 福泉市| 平遥县| 桑日县| 云林县| 普定县| 汕尾市| 东光县| 云龙县| 洪江市| 衡南县| 宜都市| 太仓市| 赞皇县| 民和| 平罗县| 共和县| 贵港市| 靖远县| 松江区| 镇安县| 汶川县| 永清县| 泸定县| 阿瓦提县| 德钦县| 汽车| 垫江县|