一、cdn引入基本使用
- template的寫法
- data屬性必須是函式
- 計算屬性的使用
- 其他屬性(props、watch、emits、setup、生命周期等)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Vue3_CND引入</title>
</head>
<body>
<div id="app">呵呵哈哈哈</div>
<!--
方式1:
<script type="x-template" id="template">
<h2>{{num}}</h2>
<h2>{{computeNum}}</h2>
<button @click="add">+</button>
<button @click="sub">-</button>
</script>
-->
<!-- 方式2: (https://developer.mozilla.org/zh-CN/docs/Web/HTML/Element/template)-->
<template id="template">
<h2>{{num}}</h2>
<h2>{{computeNum}}</h2>
<button @click="add">+</button>
<button @click="sub">-</button>
</template>
<script src="https://unpkg.com/vue@next"></script>
<script>
const data = {
template: '#template',
data() {
return {
num: 0
}
},
computed: {
computeNum() { return this.num + 1 }
},
methods: {
add() {
this.num++
},
sub() {
this.num--
}
}
}
const app = Vue.createApp(data)
app.mount('#app')
</script>
</body>
</html>
二、vue3原始碼閱讀方法
- 首先找到vue3原始碼倉庫,拉取代碼到本地
- package.json檔案夾中的腳本添加sourcemap:“dev”: “node scripts/dev.js --sourcemap”,執行yarn dev(打包dist)
- 在packages/vue/examples下隨便寫一個HTML檔案,并在其中使用vue,就可以觀察具體vue內部運行情況,
<!DOCTYPE html>
<html lang="en">
<body>
<div id="app"></div>
<script src="../dist/vue.global.js"></script>
<script>
debugger
Vue.createApp({ template: `<div></div>` }).mount('#app')
</script>
</body>
</html>
三、methods屬性中的方法this系結原始碼
vue-next原始碼packages/runtime-core/src/componentOptions.ts中的600行左右
if (methods) {
for (const key in methods) {
const methodHandler = (methods as MethodOptions)[key]
if (isFunction(methodHandler)) {
// In dev mode, we use the `createRenderContext` function to define
// methods to the proxy target, and those are read-only but
// reconfigurable, so it needs to be redefined here
if (__DEV__) {
Object.defineProperty(ctx, key, {
value: methodHandler.bind(publicThis),
configurable: true,
enumerable: true,
writable: true
})
} else {
ctx[key] = methodHandler.bind(publicThis)
}
if (__DEV__) {
checkDuplicateProperties!(OptionTypes.METHODS, key)
}
} else if (__DEV__) {
warn(
`Method "${key}" has type "${typeof methodHandler}" in the component definition. ` +
`Did you reference the function correctly?`
)
}
}
}
最重要的一步就是ctx[key] = methodHandler.bind(publicThis),將每一個methods屬性中的方法的this都系結publicThis并存到ctx物件中(在模板引擎中需要從ctx里面取相應的方法來呼叫),我們可以在原始碼中找到const publicThis = instance.proxy! as any,所以是系結的this是組件實體上的data代理物件,
四、vscode快捷添加代碼片段
首先找到vscode的user Snippets選項:

可以在snippet-generator中自動生成設定代碼:

設定完之后就可以,全域使用快捷指令:

轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/300764.html
標籤:其他
上一篇:拷貝靜態資源
下一篇:Vue報錯Module build failed Error Node Sass version 6.0.1 is incompatible with ^4.0.0.解決方案
