- Vue.js 2 Design Patterns and Best Practices
- Paul Halliday
- 368字
- 2021-06-24 18:33:05
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:

In the next section, we'll take a deeper look at debugging our Vue applications, and the role Vue devtools plays in this.
- 計算機網絡與通信(第2版)
- Modern JavaScript Web Development Cookbook
- 智能網聯汽車V2X與智能網聯設施I2X
- 異構基因共表達網絡的分析方法
- 物聯網檢驗檢測技術
- 計算機網絡安全實訓教程(第二版)
- Windows Server 2003 Active Directory Design and Implementation: Creating, Migrating, and Merging Networks
- 物聯網通信技術
- 雷達饋線技術
- 網絡基礎與網絡管理項目化教程
- C/C++串口通信:典型應用實例編程實踐
- INSTANT KineticJS Starter
- 通信十年:擁抱互聯網
- 紅藍攻防:構建實戰化網絡安全防御體系
- bash網絡安全運維