方式一:template模板
<!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>Document</title>
</head>
<body>
<div id="app"></div>
<template id="my-app">
<!-- 这里会显示为:Hello World -->
<h2>{{message}}</h2>
<!-- 相当于<h2>Hello World</h2> -->
</template>
<script src="https://unpkg.com/vue@next"></script>
<script>
const App = {
template: '#my-app',
data() {
return {
message: "Hello World",
counter: 100,
isShow: true
}
},
methods: {
getReverseMessage() {
return this.message.split(" ").reverse().join(" ");
},
toggle() {
this.isShow = !this.isShow;
}
}
}
Vue.createApp(App).mount('#app');
</script>
</body>
</html>
方式二:render函数
使用h函数来编写渲染的内容
方式三:通过.vue文件中的template(SFC)
假设这是项目中的一个叫 App.vue 的文件,这种也叫SFC,single-file components (单文件组件)。
这种方式是后续最常用的方式,也是web工程模块化写代码的方式,通过webpack、Vue Cli、Vite等打包工具构架的项目都是通过这样的方式编写。
<template>
<h2>这里编写html</h2>
<hello-world></hello-world>
<h2>{{countVue2}}</h2>
<button @click="add">点我+1</button>
<h2>{{countVue3}}</h2>
<button @click="reduce">点我-1</button>
</template>
<script>
// 这里写JavaScript
import HelloWorld from './HelloWorld.vue';
import {ref} from 'vue';
export default {
components: {
HelloWorld
},
data() { // 这是vue2写法
return {
countVue2: 0,
}
},
methods: { // 这是vue2写法
add(){
this.countVue2 += 1;
}
},
setup(){ // 这是vue3写法,data、methods等可以融入一起写
let countVue3 = ref(0)
const reduce = () => {
countVue3.value -= 1
}
return {
countVue3,
reduce,
}
}
}
</script>
<style scoped>
/* 这里是css样式 */
h2 {
color: red;
}
</style>
通过 webpack 编写Vue可以查看 Webpack
======================
Vue 中处理template
Vue文件的版本
打开我们项目下node_modules文件夹,找到vue,打开dist(这是Vue源码打包好的文件夹)文件夹,里面可以看到很多版本。
常见的就是上面的这些版本。
.runtime 版本(仅运行时)
加上.runtime 的版本,就是runtime compilation版本,这种版本不包含对template属性进行编译,因此也会更小一点。
运行时+编译器
不加.runtime 的版本,运行时+编译器版本,这种版本会稍大一点,因为包含了对template属性的编译。
.prod版本
加上.prod 的版本,就是production版本,就是生产环境下用的版本,这种版本都是经过代码压缩丑化(去掉空格换行符、替换变量名等)的版本,体积较小,但完全看不懂。
======================
VS-Code对SFC的支持
插件一:Vetur,从Vue2开发就一直在使用的VSCode支持Vue的插件,比较稳的插件,但对Vue3部分实验中的特性支持不是很好;
插件二:Volar,官方推荐的插件(后续会基于Volar开发官方的VSCode插件),但目前还不是很好用,少了很多提示,还需要完善