内容纲要

[code language=”html”]
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<script src="app.js"></script>
</body>
</html>
[/code]

页面引用 app.js 后,执行闭包脚本,添加 dom 节点

app.js
[code language=”js”]
(function() {
/**
* Outputting the value of this to the console in the global context returns the Window object.
*/
console.log(this);

/*
* This means we can either use global window objects by their name or prefixed with this:
*/
//alert(‘Alert one’);
//this.alert(‘Alert two.’);

/**
* This no longer works when we enter a new scope, take our Student object as an example:
*/
const Student = {
firstName: ‘Paul’,
lastName: ‘Halliday’,
grades: [50, 95, 70, 65, 35],
getFullName() {
return `${this.firstName} ${this.lastName}`;
},
getGrades() {
return this.grades.reduce((accumulator, grade) => accumulator + grade);
},
toString() {
return `Student ${this.getFullName()} scored ${this.getGrades()}/500`;
}
};

// Display this on web page.
let res = document.createTextNode(Student.toString());
let heading = document.createElement(‘h1’);
heading.appendChild(res);
document.body.appendChild(heading);
})();

[/code]

vue 是如何做的,相当于一个代理层,webpack 会把相关的文件编译为 dist/build.js

[code language=”html”]
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>vue-proxy</title>
</head>
<body>
<div id="app"></div>
<script src="/dist/build.js"></script>
</body>
</html>

[/code]

main.js
[code language=”js”]
import Vue from ‘vue’
import App from ‘./App.vue’

new Vue({
el: ‘#app’,
render: h => h(App)
})

[/code]

App.vue
[code language=”js”]
<template>
<button @click="showAlert">Show Alert</button>
</template>

<script>
export default {
data () {
return {
message: ‘Hello World!’
}
},
methods: {
showAlert() {
alert(this.message);
}
}
}
</script>

<style>
</style>
[/code]

发表评论

电子邮件地址不会被公开。 必填项已用*标注