三、原生Vue程序
提示:上一节我们使用vite体验了一下Vue的开发,这一节我们主要使用原生js的方式来学习vue。通过这两种方式的学习可以更好的理解vue的使用。
编写html文件
在dist中新建vue3-demo.html文件
提示:以下为内容,请读者对比上一节中的内容来理解。
<html>
<head>
<title>原生vue3演示</title>
<!--
通过script标签加载vue的js文件
相当于man.js 中的import { createApp } from 'vue'
-->
<script src="https://unpkg.com/vue@next"></script>
<style>
#app {
font-family: Avenir, Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
</style>
</head>
<!-- 对比上一节中的index.html -->
<div id="app">
<HelloWorld msg="Hello Vue 3 + Vite" />
</div>
<script>
//对比上一节里的HelloWorld.vue
var HelloWorld_vue = {
props: {
msg: String
},
data() {
return {
count: 0
}
},
template: `
<h1>{{ msg }}</h1>
<button type="button" @click="count++">count is: {{ count }}</button>
`
};
//对比上一节里的App.vue
var App_vue = {
template: `
<HelloWorld msg="Hello Vue 3 + Vite" />
`
}
//对比上一节中的main.js
//创建一个Vue 应用
var createApp = Vue.createApp(App_vue)
//注册HelloWorld组件
createApp.component('HelloWorld', HelloWorld_vue)
//挂载App到div#id
var vm = createApp.mount('#app')
</script>
</html>
通过Live server查看结果
点击按钮可以看到数字在累加。
结论
以上就是用原生js来创建的vue应用,作者写这部分内容主要是让读者可以更好的理解vue的使用。细心的读者会发现这总方式开发vue所有的内容都写在一个html中。在实际开发中要比这个demo要复杂的多,这样就会导致文件过大无法协同工作和难于维护。所以在日常的开发中还是推荐使用vite来做开发与构建。