基于全局构建版本和ES模块构建版本的vue3 快速上手
不使用脚手架工具,开发Vue3,分别用全局构建版本的Vue.js和ES模块构建版本的Vue.js,并结合选项式AP和组合式API,介绍快速入门。
使用全局构建版本
下载全局构建版本的 Vue,该版本的所有顶层 API 都以属性的形式暴露在了全局的 Vue 对象上。这里有一个使用全局构建版本的例子:
-
选项式 API (Options API)
<head> <meta charset="UTF-8" /> <title>Document</title> <script src="./scripts/vue.global.js"></script> </head> <body> <div id="app"> <p>{{msg}}</p> <p>姓名:{{name}}</p> 姓名:<input type="text" v-model="name" /><br /> <p>Count: {{count}}</p> <button @click="add" style="font-size: 20px">加1</button> </div> <script> const { createApp } = Vue; const app = createApp({ data() { return { msg: "Hello, Vue3", name: "Jack", count: 10, }; }, methods: { add() { this.count++; }, }, }); app.mount("#app"); </script> </body> |
-
组合式 API (Composition API)
<head> <meta charset="UTF-8" /> <title>Document</title> <script src="./scripts/vue.global.js"></script> </head> <body> <div id="app"> <p>Message: {{message}}</p> <p>Count: {{count}}</p> <button @click="add">+1</button> </div> <script> const { createApp, ref } = Vue; createApp({ setup() { message = ref("Hello, world"); count = ref(1); function add() { count.value += 1; } return { message, count, add }; }, }).mount("#app"); </script> |
使用 ES 模块构建版本
更常用的是 ES 模块语法。现代浏览器大多都已原生支持 ES 模块。因此可以像这样通过 CDN 以及原生 ES 模块使用 Vue:
组合式 API (Composition API)
启用 Import maps方式引用,或者直接from中引入,都可以!
<head> <meta charset="UTF-8" /> <title>Document</title> <!-- <script type="importmap"> { "imports": { "vue": "./scripts/vue.esm-browser.js" } } </script> --> </head> <body> <div id="app"> <p>{{msg}}</p> <button @click="change">更改</button> </div> <script type="module"> // import { createApp, ref } from "vue"; import { createApp, ref } from "./scripts/vue.esm-browser.js"; const App = { setup() { let msg = ref("Jack"); function change() { msg.value = "Kerwin"; } return { msg, change }; }, }; createApp(App).mount("#app"); </script> |
拆分模块
官网例子:
<body> <div id="app"></div> <script type="module"> import { createApp } from "./scripts/vue.esm-browser.js"; import MyComponent from "./test06_component.js"; createApp(MyComponent).mount("#app"); </script> </body> |
import { ref } from "./scripts/vue.esm-browser.js"; export default { setup() { let msg = ref("Jack"); let count = ref(10); function add() { count.value += 1; } return { msg, count, add }; }, template: ` <div> <p>Message: {{msg}}</p> <p>Count: {{count}}</p> <button @click="add">计数加1</button> </div> `, }; |