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

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.

主站蜘蛛池模板: 石首市| 天台县| 陆川县| 蚌埠市| 绵竹市| 伊川县| 鹰潭市| 社会| 镇巴县| 蓝山县| 商城县| 柳河县| 阆中市| 南投市| 公安县| 外汇| 成都市| 四平市| 富源县| 安庆市| 英德市| 苗栗市| 辽宁省| 罗城| 招远市| 民丰县| 盐城市| 正镶白旗| 三穗县| 鹤岗市| 沙坪坝区| 孙吴县| 云霄县| 商丘市| 祁阳县| 昌乐县| 闻喜县| 灵丘县| 和田县| 马山县| 德化县|