优秀的编程知识分享平台

网站首页 > 技术文章 正文

Vue.js学习笔记 | 01.使用template创建组件

nanyue 2025-01-02 18:09:14 技术文章 2 ℃

1、创建一个HTML文件

创建一个新的HTML文件,文件名为template.htmltemplate.html文件的初始内容为模板文件的内容。

2、在<script>标签中使用解构赋值语法,从Vue对象中提取defineComponentcreateApp方法,将它们赋值给变量defineComponentcreateApp中。其中createApp用于创建Vue实例,defineComponent用于定义组件。

 const {
   defineComponent,
   createApp
 } = Vue;

3、使用defineComponent方法定义一个组件,defineComponent方法的参数为一个JavaScript对象。在本示例中,我们使用了datamethodstemplate3个属性。

 const component = defineComponent({
   data: () => ({
     // 定义一个属性,用于计数
     count: 0
   }),
   methods: {
     // 定义方法,调用时count属性加1
     addOne() {
       this.count += 1;
     }
   },
   // 组件模板
   template: `
     <h1>Vue 3 根元素</h1>
     <button @click="addOne">点了{{ count }}次</button>
   `
 });

data属性是一个单例函数,返回了一个JavaScript对象,这个JavaScript对象中包含一个count属性,count属性默认值为0

methods属性是一个对象。在methods属性中创建一个名为addOne的属性,它是一个函数,用于将count的值增加1

template属性的值为字符串时,字符串将作为模板的内容嵌入到组件中。在上面的template属性,我们创建了一个<h1>元素和一个<button>按钮,<h1>元素用于展示标题,<button>按钮绑定了一个单击事件,点击时触发addOne()函数。

4、创建vue实例

使用createApp创建vue实例,将vue实例挂载到HTML DOM元素上。

 createApp(component).mount('#app');

使用createApp创建vue实例,参数为前面创建的组件。vue实体用于管理和挂载组件。调用mount()方法将vue实例挂载到HTML DOM元素上。


template.html完整内容:

 <!doctype html>
 <html lang="en">
 <head>
   <meta charset="UTF-8">
   <meta name="viewport" content="width=device-width, user-scalable=no, 
     initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
   <meta http-equiv="X-UA-Compatible" content="ie=edge">
   <title>使用template创建组件</title>
   <script src="https://unpkg.com/vue@next"></script>
 </head>
 <body>
   <div id="app">
   </div>
   <script>
     // 从Vue对象中解构出defineComponent和createApp方法,将它们保存到变量中
     const {
       defineComponent,
       createApp
     } = Vue;
     // 定义一个属性
     const component = defineComponent({
       data: () => ({
         // 定义一个属性,用于计数
         count: 0
       }),
       methods: {
         // 定义方法,调用时count属性加1
         addOne() {
           this.count += 1;
         }
       },
       // 组件模板
       template: `
         <h1>Vue 3 根元素</h1>
         <button @click="addOne">点了{{ count }}次</button>
       `
     });
     // 使用createApp创建vue实例,实体用于管理和挂载组件
     // 将vue实例挂载到HTML DOM元素上
     createApp(component).mount('#app');
   </script>
 </body>
 </html>



最近发表
标签列表