方式一:template模板

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta http-equiv="X-UA-Compatible" content="IE=edge">
  6. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  7. <title>Document</title>
  8. </head>
  9. <body>
  10. <div id="app"></div>
  11. <template id="my-app">
  12. <!-- 这里会显示为:Hello World -->
  13. <h2>{{message}}</h2>
  14. <!-- 相当于<h2>Hello World</h2> -->
  15. </template>
  16. <script src="https://unpkg.com/vue@next"></script>
  17. <script>
  18. const App = {
  19. template: '#my-app',
  20. data() {
  21. return {
  22. message: "Hello World",
  23. counter: 100,
  24. isShow: true
  25. }
  26. },
  27. methods: {
  28. getReverseMessage() {
  29. return this.message.split(" ").reverse().join(" ");
  30. },
  31. toggle() {
  32. this.isShow = !this.isShow;
  33. }
  34. }
  35. }
  36. Vue.createApp(App).mount('#app');
  37. </script>
  38. </body>
  39. </html>

方式二:render函数

使用h函数来编写渲染的内容

方式三:通过.vue文件中的template(SFC)

假设这是项目中的一个叫 App.vue 的文件,这种也叫SFC,single-file components (单文件组件)。

这种方式是后续最常用的方式,也是web工程模块化写代码的方式,通过webpack、Vue Cli、Vite等打包工具构架的项目都是通过这样的方式编写。

  1. <template>
  2. <h2>这里编写html</h2>
  3. <hello-world></hello-world>
  4. <h2>{{countVue2}}</h2>
  5. <button @click="add">点我+1</button>
  6. <h2>{{countVue3}}</h2>
  7. <button @click="reduce">点我-1</button>
  8. </template>
  9. <script>
  10. // 这里写JavaScript
  11. import HelloWorld from './HelloWorld.vue';
  12. import {ref} from 'vue';
  13. export default {
  14. components: {
  15. HelloWorld
  16. },
  17. data() { // 这是vue2写法
  18. return {
  19. countVue2: 0,
  20. }
  21. },
  22. methods: { // 这是vue2写法
  23. add(){
  24. this.countVue2 += 1;
  25. }
  26. },
  27. setup(){ // 这是vue3写法,data、methods等可以融入一起写
  28. let countVue3 = ref(0)
  29. const reduce = () => {
  30. countVue3.value -= 1
  31. }
  32. return {
  33. countVue3,
  34. reduce,
  35. }
  36. }
  37. }
  38. </script>
  39. <style scoped>
  40. /* 这里是css样式 */
  41. h2 {
  42. color: red;
  43. }
  44. </style>

通过 webpack 编写Vue可以查看 Webpack

======================

Vue 中处理template

image.png

Vue文件的版本

image.png
打开我们项目下node_modules文件夹,找到vue,打开dist(这是Vue源码打包好的文件夹)文件夹,里面可以看到很多版本。
image.png image.png
常见的就是上面的这些版本。

.runtime 版本(仅运行时)

加上.runtime 的版本,就是runtime compilation版本,这种版本不包含对template属性进行编译,因此也会更小一点。

运行时+编译器

不加.runtime 的版本,运行时+编译器版本,这种版本会稍大一点,因为包含了对template属性的编译。

.prod版本

加上.prod 的版本,就是production版本,就是生产环境下用的版本,这种版本都是经过代码压缩丑化(去掉空格换行符、替换变量名等)的版本,体积较小,但完全看不懂。

======================

VS-Code对SFC的支持

插件一:Vetur,从Vue2开发就一直在使用的VSCode支持Vue的插件,比较稳的插件,但对Vue3部分实验中的特性支持不是很好;

插件二:Volar,官方推荐的插件(后续会基于Volar开发官方的VSCode插件),但目前还不是很好用,少了很多提示,还需要完善