Vue3入门指南:零基础小白也能轻松理解的学习笔记

news2024/10/6 1:34:43

文章目录

  • 创建项目
  • 开发环境
  • 项目目录
  • 模板语法
  • 属性绑定
  • 条件渲染
  • 列表渲染
  • 事件处理
    • 内联事件处理器
    • 方法事件处理器(常用)
  • 事件参数
    • 获取 event 事件
    • 事件传参
  • 事件修饰符
    • 阻止默认事件
    • 阻止事件冒泡
  • 数组变化侦测
    • 变更方法
    • 替换一个数组
  • 计算属性
  • class 绑定
  • 单对象绑定
  • 多对象绑定
    • 绑定数组
  • Style 绑定
  • 侦听器
  • 表单输入绑定
    • 单选框
    • 复选框
    • 修饰符
  • 模板引用(操作 DOM)
  • 组件组成
    • 组成结构
    • 案例
  • 组件嵌套关系
    • Header.vue
    • Main.vue
    • Aside.vue
    • Article.vue
    • Item
  • 组件注册方式
    • 全局注册
    • 局部注册
  • 组件传递数据
    • 静态传递数据
    • 动态传递数据
  • 组件传递多种数据类型
  • 组件传递数据 Props 校验
  • 组件事件
    • 组件事件配合 V-model
    • 组件数据传递
    • 透传 Attributes
  • 插槽
    • 插槽 Slots
      • 插槽 Slots
      • 具名插槽传递数据
  • 组件的声明周期
    • 声明周期的应用
  • 动态组件
  • 组件保持存活
  • 异步组件
  • 依赖注入
  • Vue应用
  • 路由

创建项目

  • 配置 node.js > 15.0
  • 命令行创建命令 npm init vue@latest
  • cd 项目名
  • npm install
  • npm run dev
  • cnpm下载方法,更快
  • 设置 VSCode 自动保存
  • 官方教程

开发环境

  • VSCode + Volar
  • 格式化代码:Shift + Alt + F

项目目录

  • .vscode:VSCode工具的配置文件
  • node_modules:Vue项目运行的依赖文件
  • public:资源文件夹(浏览器图标)
  • src:源码文件夹
  • .gitignore:git忽略文件
  • index. html:入口HTML文件
  • package. json:信息描述文件
  • README. md:注释文件
  • vite.config.js:Vue配置文件

模板语法

<template>
  <h3>模板语法</h3>
  <p>{{ msg }}</p>
</template>

<script>
export default{
  data(){
    return {
      msg:"神奇的魔法"
    }
  }
}
</script>
  • 绑定仅支持单一表达式:简单算数,三目运算法,链式调用,能写在 return 后面
  • 想插 HTML,需要使用 v-html

属性绑定

<template>
  <div v-bind:id="dynamicId" v-bind:class="dynamicClass">属性绑定</div>
</template>

<script>
export default{
  data(){
    return{
      dynamicClass:"appClass",
      dynamicId:"appId"
    }
  }
}
</script>

<style>
.appClass{
  color:red;
  font-size: 30px;
}
</style>
  • v-bind 可以简写为:
  • 动态绑定多个值
<template>
  <div v-bind="objectOfAttrs">属性绑定</div>
</template>

<script>
export default{
  data(){
    return{
      objectOfAttrs:{
        class:"appclass",
        id:"appid"
      }
    }
  }
}
</script>

<style>
.appclass{
  color:red;
  font-size: 30px;
}
</style>

条件渲染

<template>
  <h3>条件渲染</h3>
  <div v-if="flag">你能看见我吗?</div>
  <div v-else>那你还是看看我吧</div>
</template>

<script>
export default{
  data(){
    return{
      flag:false
    }
  }
}
</script>
<template>
  <h3>条件渲染</h3>
  <div v-if="type==='A'">A</div>
  <div v-else-if="type==='B'">B</div>
  <div v-else-if="type==='C'">C</div>
  <div v-else>Not A/B/C</div>

</template>

<script>
export default{
  data(){
    return{
      type:'D'
    }
  }
}
</script>
  • v-show 和 v-if 一样但不能配合 v-else
  • v-show 有较高初始开销,v-if 有较高切换开销

列表渲染

<template>
  <h3>列表渲染</h3>
  <p v-for="item in names">{{ item }}</p>
</template>

<script>

export default{
  data(){
      return{
          names:["百战程序员","尚学堂","IT"]
      }
  }
}
</script>
<template>
  <h3>列表渲染</h3>
  <div v-for="item in result">
    <p>{{item.title}}</p>
    <img v-bind:src="item.avatar" alt="">
  </div>
</template>

<script>

export default {
  data() {
    return {
      result: [
        {
          "id": 2261677,
          "title": "鄂尔多斯|感受一座城市的璀璨夜景感受一座城市,除了白日里的车水马龙,喧嚣繁华",
          "avatar": "https://pic.qyer.com/avatar/002/25/77/30/200?v=1560226451"
        },
        {
          "id": 2261566,
          "title": "成都这家洞穴暗黑风咖啡厅酷毙了!早C晚A走起\n成都天气这么热\n咖啡\n人必",
          "avatar": "https://pic.qyer.com/avatar/011/07/08/69/200?v=1572185180"
        },
        {
          "id": 2261662,
          "title": "【川西新龙-措卡湖】措卡湖,意为“乱石丛中的黑色海水”,神秘小众原汁原味。深",
          "avatar": "https://pic.qyer.com/avatar/009/88/48/58/200?v=1507386782"
        }
      ]
      
    }
  }
}
</script>
  • items 可以提取出更多内容 (value,key,index)
  • in 可以用 of 来替换
  • 通过 :key=“item.id” 管理状态,保证数组变化时,不进行重新渲染

事件处理

内联事件处理器

<template>
  <h3>内联事件处理器</h3>
  <!-- <button v-on:click="count++">Add</button> -->
  <button @click="count++">Add</button>
  <p>{{count }}</p>
</template>

<script>
export default{
  data(){
    return{
      count:0
    }
  }
}
</script>

方法事件处理器(常用)

<template>
  <h3>方法事件处理器</h3>
  <button @click="addCount">Add</button>
  <p>{{count }}</p>
</template>

<script>
export default{
  data(){
    return{
      count:0
    }
  },
  //所有的方法函数都放在这里
  methods:{
    addCount(){
      this.count++;
      console.log("点击了")
    }
  }
}
</script>

事件参数

获取 event 事件

<template>
  <h3>Vue 中的 event 对象就是原生的 event</h3>
  <button @click="addCount">Add</button>
  <p>{{count }}</p>
</template>

<script>
export default{
  data(){
    return{
      count:0
    }
  },
  //所有的方法函数都放在这里
  methods:{
    addCount(event){
      this.count++;
      event.target.innerHTML="Add"+this.count;
    }
  }
}
</script>

事件传参

<template>
  <h3>事件传参</h3>
  <p @click="getNameHandle(item, $event)" v-for="(item, index) of names" :key="index">{{ item }}</p>
</template>

<script>
export default {

  data() {
    return {
      names: ["iwen", "ime", "frank"]
    }
  },


  //所有的方法函数都放在这里
  methods: {
    getNameHandle(name, e) {
      console.log(name, e);
    }
  }
}
</script>

事件修饰符

阻止默认事件

<template>
 <h3>事件修饰符</h3>
 <a @click.prevent="clickHandle" href="https://itbaizhan.com">百战程序员</a>
</template>

<script>
export default{
  data(){
    return{

    }
  },
  methods:{
    clickHandle(e){
      //阻止默认事件
      // e.preventDefault();
      console.log("点击了");
    }
  }
}
  
</script>

阻止事件冒泡

<template>
 <h3>事件修饰符</h3>
 <div @click="clickDiv">
  <p @click.stop="clickP">测试冒泡</p>
 </div>
</template>

<script>
export default{
  data(){
    return{

    }
  },
  methods:{
    clickDiv(){
      console.log("div");
    },
    clickP(){
      console.log("P");
    }
  }
}
</script>

数组变化侦测

变更方法

  • push
  • pop
  • shift
  • unshift
  • splice
  • sort
  • reverse

替换一个数组

  • filter
  • concat
  • slice
<template>
 <h3>数组变化侦听</h3>
 <button @click="addListHandle"></button> 
 <ul>
    <li v-for="(item,index) of names" :key="index">{{  item }}</li>
  </ul>
  <button @click="concatHandle">合并数组</button>
  <h3>数组1</h3>
  <p v-for="(item,index) of nums1" :key="index">{{ item }}</p>
  <h3>数组 2</h3>
  <p v-for="(item,index) of nums2" :key="index">{{ item }}</p>
</template>

<script>
export default{
  data(){
    return{
      names:["iwen","ime","frank"],
      nums1:[1,2,3,4,5],
      nums2:[6,7,8,9,10]
    } 
  },
  methods:{
    addListHandle(){
      //会引起 UI 自动更新
      // this.names.push("sarra")
      //不会引起 UI 自动更新
      //this.names.concat(["sarra"])
      this.names = this.names.concat(["sarra"])
    },
    concatHandle(){
      this.nums1 = this.nums1.concat(this.nums2)
    }
  }
}
</script>

计算属性

  • 没引入计算属性,不推荐
<template>
  <h3>{{  itbaizhan.name }}</h3>
  <p>{{ itbaizhan.content.length>0?'Yes':'No' }}</p>
</template>

<script>
export default{
  data(){
    return{
      itbaizhan:{
        name:"百战程序员",
        content:["前端","Java","Python"]
      }
    }
  }
}
</script>
  • 引入计算属性
<template>
  <h3>{{  itbaizhan.name }}</h3>
  <p>{{ itbaizhanContent }}</p>
</template>

<script>
export default{
  data(){
    return{
      itbaizhan:{
        name:"百战程序员",
        content:["前端","Java","Python"]
      }
    }
  },
  computed:{
    itbaizhanContent(){
        return this.itbaizhan.content.length>0?'Yes':'No'
    }
  }
}
</script>
  • 计算属性会基于响应式依赖被缓存,一个计算属性仅会在响应式依赖更新时才会被重新计算
  • 方法:会在重新渲染发生时再次执行函数

class 绑定

单对象绑定

<template>
  <p :class="{ 'active':isActive,'text-danger':hasError}">Class 样式绑定</p>
</template>

<script>
export default{
  data(){
    return{
      isActive:false
    }
  },

}
</script>

<style>
.active{
  color: red;
  font-size: 30px;
}
</style>
<template>
  <p :class="{ 'active':isActive,'text-danger':hasError}">Class 样式绑定</p>
</template>

<script>
export default{
  data(){
    return{
      isActive:true,
      hasError:true
    }
  },

}
</script>

<style>
.active{

  font-size: 30px;
}

.text-danger{
  color: red;
}
</style>

多对象绑定

<template>
  <p :class="classObject">Class 样式绑定</p>
</template>

<script>
export default{
  data(){
    return{
      classObject:{
        'active':true,
        'text-danger':false
      }
    }
  },

}
</script>

<style>
.active{

  font-size: 30px;
}

.text-danger{
  color: red;
}
</style>

绑定数组

<template>
  <p :class="[arrActive,arrHasError]">Class 样式绑定</p>
</template>

<script>
export default{
  data(){
    return{
      arrActive:"active",
      arrHasError:"text-danger"
    }
  },

}
</script>

<style>
.active{
  font-size: 30px;
}

.text-danger{
  color: red;
}
</style>
  • 数组可以用三目运算符
  • 数组和对象可以嵌套

Style 绑定

<template>
  <div :style="{color:activeColor,fontSize:fontSize+'px'}">Style绑定</div>
</template>

<script>
export default{
  data(){
    return{
      activeColor:'red',
      fontSize:30
    }
  }
}
</script>
<template>
  <div :style="styleObject">Style绑定</div>
</template>

<script>
export default{
  data(){
    return{
      styleObject:{
        color:'red',
        fontSize:'30px'
      }
    }
  }
}
</script>
  • 绑定数组(多余)

侦听器

<template>
  <h3>侦听器</h3>
  <p>{{ message }}</p>
  <button @click="updateHandle">修改数据</button>
</template>

<script>
export default{
  data(){
    return{
      message:"Hello"
    }
  },
  methods:{
    updateHandle(){
      this.message = "World"
    }
  },
  watch:{
    message(newValue,oldValue){
      console.log(newValue,oldValue)
    }
  }

}
</script>

表单输入绑定

单选框

<template>
  <input type="text" v-model="message">
  <p>{{ message }}</p>
</template>

<script>
export default{
  data(){
    return{
      message:""
    }
  }
}
</script>

复选框

<template>
  <input type="checkbox" id="checkbox" v-model="checked"/>
  <label for="checkbox">{{  checked }}</label>
</template>

<script>
export default{
  data(){
    return{
      message:"",
      checked:false
    }
  }
}
</script>

修饰符

  • .lazy
  • .number
  • .trim
  • 失去焦点后显示:
<template>
  <input type="text" v-model.lazy="message">
  <p>{{ message }}</p>
</template>

<script>
export default{
  data(){
    return{
      message:""
    }
  }
}
</script>

模板引用(操作 DOM)

  • 内容改变:{{ 模板语法 }}
  • 属性改变:v-bind:指令
  • 事件:v-on:click
  • 如果没有特别的需求不要操纵 DOM
<template>
  <div ref="container" class="container">{{ content }}</div>
  <button @click="getElementHandle">获取元素</button>
  <input type="text" ref="username">
</template>

<script>
export default{
  data(){
    return{
      content:"内容"
    }
  },
  methods:{
    getElementHandle(){
      this.$refs.container.innerHTML = "hahaha";
      console.log(this.$refs.username.value)
    }
  }
}
</script>

组件组成

  • Vue 会单独定义在.Vue 中,叫单文件组件(SFL)

组成结构

  • scoped让当前样式只在当前文件中生效,局部样式
<template>
  <div>承载标签</div>
</template>

<script>
export default{}
</script>

<style scoped>
</style>

案例

  • MyComponent.vue
<template>
  <div class="container">{{ message }}</div>
</template>

<script>
export default{
  data(){
    return{
      message:"组件基础组成"
    }
  }
}
</script>

<style>
.container{
  font-size:'30px';
  color:red;
}
</style>
  • App.vue
<template>
  <!--3 标注组件 -->
  <MyComponent/>
</template>

<script>
//1 引入组件
import MyComponent from "./components/MyComponent.vue"

export default{
  //2 注入组件
  components:{
    MyComponent
  }
}
</script>

<style>

</style>

组件嵌套关系

在这里插入图片描述

Header.vue

<template>
    <h3>Header</h3>
</template>

<style scoped>
h3{
    width:100%;
    height: 100px;
    border: 5px solid #999;
    text-align: center;
    line-height: 100px;
    box-sizing: border-box;
}
</style>

Main.vue

<template>
    <div class="main">
        <h3>Main</h3>
        
    </div>
</template>

<script>
import Article from './Article.vue';
export default{
    components:{
        Article
    }
}
</script>

<style scoped>
.main{
    float: left;
    width: 70%;
    height: 400px;
    border: 5px solid #999;
    box-sizing: border-box;
    border-top: 0px;
}
</style>

Aside.vue

<template>
    <div class="aside">
        <h3>Aside</h3>
        <Item/>
        <Item/>
        <Item/>
    </div>
</template>
<script>
import Item from './Item.vue'
export default{
    components:{
        Item
    }
}
</script>

<style scoped>
.aside{
    float: right;
    width:30%;
    height: 600px;
    border: 5px solid #999;
    box-sizing: border-box;
    border-left: 10;
    border-top: 10;
}
</style>

Article.vue

<template>
    <h3>Article</h3>
</template>

<style scoped>
h3{
    width: 80%;
    margin:0 auto;
    text-align: center;
    line-height: 100px;
    box-sizing: border-box;
    margin-top: 50px;
    background: #999;
}
</style>

Item

<template>
    <h3>Item</h3>
</template>

<style scoped>
h3{
    width:80%;
    margin:0 auto;
    text-align: center;
    line-height: 100px;
    box-sizing: border-box;
    margin-top: 10px;
    background: #999;
}
</style>

组件注册方式

全局注册

最外层注册全局都能用 Main.js 中

import { createApp } from 'vue'
import App from './App.vue'
import Header from './pages/Header.vue'

const app = createApp(App)

app.component("Header",Header)

app.mount("#app")=

局部注册

如上节

  • 如果没用该组件,打包会带上
  • 大型项目中可维护性低

组件传递数据

  • 解决方案:props

静态传递数据

  • App.vue
<template>
  <Parent/>
</template>

<script>
import Parent from './components/parent.vue'
export default{
  components:{
    Parent
  }
}
</script>

<style>

</style>
  • Parent.vue
<template>
    <h3>Parent</h3>
    <Child title="parent 数据" demo="测试"/>
</template>

<script>
import Child from './child.vue'
export default{
    data(){
        return{

        }
    },
    components:{
        Child
    }
}
</script>
  • Child.vue
<template>
    <h3>Child</h3>
    <p>{{ title }}</p>
    <p>{{ demo }}</p>
</template>

<script>
export default{
    data(){
        return{
            
        }
    },
    props:["title","demo"]
}
</script>

动态传递数据

  • parent.vue
<template>
    <h3>Parent</h3>
    <Child :title="message"/>
</template>

<script>
import Child from './child.vue'
export default{
    data(){
        return{
            message:"Parent 数据!"
        }
    },
    components:{
        Child
    }
}
</script>
  • child.vue
<template>
    <h3>Child</h3>
    <p>{{ title }}</p>
</template>

<script>
export default{
    data(){
        return{
            
        }
    },
    props:["title"]
}
</script>
  • props 传递数据只能父级传递给子级,不能相反

组件传递多种数据类型

  • 任何类型
  • parent.vue
<template>
    <h3>Parent</h3>
    <Child :title="message" :age="age" :names="names" :userInfo="userInfo"/>
</template>

<script>
import Child from './child.vue'
export default{
    data(){
        return{
            message:"Parent 数据!",
            age:10,
            names:["iwen","jixiyu"],
            userInfo:{
                name:"iwen",
                age:20
            }
        }
    },
    components:{
        Child
    }
}
</script>
  • child.vue
<template>
    <h3>Child</h3>
    <p>{{ title }}</p>
    <p>{{  age }}</p>
    <ul>
        <li v-for="(item,index) of names" :key="index">{{ item }}</li>
    </ul>
    <p>{{ userInfo.name }}</p>
    <p>{{ userInfo.age }}</p>
</template>

<script>
export default{
    data(){
        return{
            
        }
    },
    props:["title","age","names","userInfo"]
}
</script>

组件传递数据 Props 校验

  • 默认值,类型校验,必选项
  • Props 传递来的数据是只读的
<template>
    <h3>ComponentA</h3>
    <ComponentB :title="title" :names="names"/>
</template>

<script>
import ComponentB from "./ComponentB.vue"
export default{
    data(){
        return{
            title:"title",
            names:["awin","jiangxiyu"]
        }
    },
    components:{
        ComponentB
    }
}
</script>

组件事件

  • 子元素数据传递给父级数据 this.$emit
  • 父级数据传递给子数据 props
  • Child.vue
<template>
    <h3>Child</h3>
    <button @click="clickEventHandle">传递数据</button>
</template>

<script>
export default{
    data(){
        return{
            msg:"Child 数据!"
        }
    },
    methods:{
        clickEventHandle(){
            this.$emit("someEvent",this.msg)
        }
    }
}
</script>
  • ComponentEvent.vue
<template>
    <h3>组件事件</h3>
    <Child @someEvent="getHandle"></Child>
    <p>父元素:{{ message }}</p>
</template>
<script>
import Child from './child.vue'
export default{
    data(){
        return {
            message:""
        } 
    },
    components:{
        Child
    },
    methods:{
        getHandle(data){
            this.message = data;
        }
    }
}
</script>

组件事件配合 V-model

  • 子组件不断发送数据给父组件,并且实时展示
  • SearComponent.vue
<template>
    搜索:<input type="text" v-model="search">
</template>

<script>
export default{
    data(){
        return{
            search:""
        }
    },
    watch:{
        search(newValue,oldValue){
            this.$emit("searchEvent",newValue)
        }
    }
}
</script>
  • Main.vue
<template>
    <h3>Main</h3>
    <p>搜索内容为:{{ search }}</p>
    <SearchCompoent @searchEvent="getSearch"/>
</template>

<script>
import SearchCompoent from './SearchCompoent.vue';
export default{
    components:{
        SearchCompoent
    },
    data(){
        return{
            search:""
        }
    },  
    methods:{
        getSearch(data){
            this.search = data;
        }
    }
}
</script>

组件数据传递

  • props 额外操作方式子传父,函数回调
  • ComponentA.vue
<template>
    <h3>ComponentA</h3>
    <p>父元素:{{ message }}</p>
    <ComponentB title="标题" :onEvent="dataFn"/>
</template>

<script>
import ComponentB from './ComponentB.vue'
export default{
    data(){
        return {
            message:""
        }
    },
    components:{
        ComponentB,
    },
    methods:{
        dataFn(data){
            this.message = data
        }
    }
}
</script>
  • ComponentB.vue
<template>
    <h3>ComponentB</h3>
    <p>{{ title }}</p>
    <p>{{  onEvent('传递数据') }}</p>
</template>

<script>
export default{
    data(){
        return {

        }
    },
    props:{
        title:String,
        onEvent:Function
    }
}
</script>

透传 Attributes

  • 使用率低,了解
  • “透传attribute"指的是传递给一个组件却没有被该组件声为props或emits的attribute或者 v-on事件
    监听器。最常见的例子就是class、style和id
  • 当一个组件以单个元素为根作渲染时,透传的attribute会自动被添加到根元素上
  • 父组件
<template>
  <AttrComponents class="attr-containder"/>
</template>

<script>
import AttrComponents from './components/AttrComponents.vue'

export default{
  components:{
    AttrComponents
  }
}
</script>

<style>

</style>
  • 子组件
<template>
    <!-- 透传属性必须唯一根元素 -->
    <h3>透传属性</h3>
</template>

<script>
export default{
    inheritAttrs:false
}
</script>

<style>
.attr-containder{
    color:red
}
</style>

插槽

  • 传递模板,子组件渲染
  • slot 插槽出口
  • App.vue
    在这里插入图片描述
<template>
  <SlotsBase>
    <div>
      <h3>插槽标题</h3>
      <p>插槽内容</p>
    </div>
  </SlotsBase>
</template>

<script>
import SlotsBase from './components/SlotsBase.vue'
export default{
  components:{
    SlotsBase
  }
}
</script>

<style>

</style>
  • SlotsBase.vue
<template>
    <slot></slot>
    <h3>插槽基础知识</h3>
</template>

插槽 Slots

  • 插槽中的数据应该在父元素内容
  • 插槽默认值,在 slot 中直接写
  • 具名插槽
    • v-slot间写为#
  • App.vue
<template>
  <SlotsTow>
    <template v-slot:header>
      <h3>{{ message }}</h3>
    </template>
    <template v-slot:main>
      <p>内容</p>
    </template>
  </SlotsTow>
</template>

<script>
import SlotsTow from './components/SlotsTow.vue'
export default{
  components:{
    SlotsTow
  },
  data(){
    return{
      message:"插槽内容续集"
    }
  }
}
</script>

<style>

</style>
  • SlotsTow.vue
<template>
    <h3>Slots插槽续集</h3>
    <slot name="header">插槽默认值</slot>
    <hr>
    <slot name="main">插槽默认值</slot>
</template>

插槽 Slots

  • 子元素数据传给父插槽

在这里插入图片描述

<template>
  <SlotsAttr v-slot="slotProps">
    <h3>{{  currentTest }} - {{  slotProps.msg }}</h3>
  </SlotsAttr>
</template>

<script>
import SlotsAttr from './components/SlotsAttr.vue'
export default{
  data(){
    return{
      currentTest:"测试内容"
    }
  },
  components:{
    SlotsAttr
  }
}
</script>

<style>

</style>
<template>
    <h3>Slots 再续集</h3>
    <slot :msg="childMessage"></slot>
</template>

<script>
export default{
    data(){
        return{
            childMessage:"子组件数据"
        }
    }
}
</script>

具名插槽传递数据

在这里插入图片描述

<template>
  <SlotsAttr>
    <template #header="slotProps">
      <h3>{{ currentTest }}-{{ slotProps.msg }}</h3>
    </template>
    <template #main="slotProps">
      <p>{{ slotProps.job }}</p>
    </template>
  </SlotsAttr>
</template>

<script>
import SlotsAttr from './components/SlotsAttr.vue'
export default{
  data(){
    return{
      currentTest:"测试内容"
    }
  },
  components:{
    SlotsAttr
  }
}
</script>

<style>

</style>
<template>
    <h3>Slots 再续集</h3>
    <slot name="header" :msg="childMessage"></slot>
    <slot name="main" :job="jobMessage"></slot>
</template>

<script>
export default{
    data(){
        return{
            childMessage:"子组件数据",
            jobMessage:"itbaizhan"
        }
    }
}
</script>

组件的声明周期

在这里插入图片描述

  • 创建:创建后系统才开始初始化数据
  • 渲染:显示
  • 更新:用户操作导致改变,渲染和显示
  • 销毁
<template>
  <h3>组件的声明周期</h3>
  <p>{{ message }}</p>
  <button @click="updateHandle"></button>
</template>

<script>
export default{
  methods:{
    updateHandle(){
      this.message = "更新之后"
    }
  },
  data(){
    return{
      message:"更新之前"
    }
  },
  beforeCreate(){
    console.log("组件创建之前")
  },
  created(){
    console.log("组件创建之后")
  },
  beforeMount(){
    console.log("组件渲染之前")
  },
  mounted(){
    console.log("组件渲染之后")
  },
  beforeUpdate(){
    console.log("组件更新之前")
  },
  updated(){
    console.log("组件更新之后")
  },
  beforeUnmount(){
    console.log("组件销毁之前")
  },
  unmounted(){
    console.log("组件销毁之后")
  }
}
</script>
<style>

</style>

声明周期的应用

  • 模拟网络请求渲染数据
  • 通过 ref 获取 dom 结构
<template>
  <UserComponent/>
</template>

<script>
import UserComponent from './components/UserComponent.vue'
export default{
  components:{
    UserComponent
  }
}
</script>
<style>

</style>
<template>
    <h3>组件声明周期函数应用</h3>
    <p ref="name">百战程序员</p>
  </template>
  
  <script>
  export default{
    beforeMount(){
      console.log(this.$refs.name);
    },
    mounted(){
      console.log(this.$refs.name)
    }
  }
  </script>
  <style>
  
  </style>
  • 读取 HTML 的过程放到页面渲染之后
  • 并且在渲染页面后再渲染数据
<template>
    <h3>组件声明周期函数应用</h3>
    <p ref="name">百战程序员</p>
    <ul>
        <li v-for="(item, index) of banner" :key ="index">
            <h3>{{ item.title }}</h3>
            <p>{{ item.content }}</p>
        </li>
    </ul>
</template>
  
<script>
export default {
    data() {
        return {
            banner: []
        }
    },
    mounted() {
        //网络请求
        this.banner = [
            {
                "title": "我在爱尔兰",
                "content": "爱尔兰(爱尔兰语: Poblacht na hEireann;英语: Republic of Ireland),是一个..."
            },
            {
                "title": "一个人的东京",
                "content": "东京(Tokyo)是日本国的首都,是亚洲第一大城市,世界第二大城市。全球最的经济中心..."
            },
            {
                "title": "普罗旺斯的梦",
                "content": "普罗旺斯(Provence)位于法国东南部,毗邻地中海和意大利,从地中海沿岸延伸到内陆..."
            }
        ]
    },
}
</script>
<style></style>

动态组件

<template>
  <ComponentA/>
  <ComponentB/>
  <component :is="tabComponent"></component>
  <button @click="changeHandle">切换组件</button>
</template>

<script>
import ComponentA from './components/ComponentA.vue'
import ComponentB from './components/ComponentB.vue'
export default{
  data(){
    return{
      tabComponent: "ComponentA"
    }
  },
  components:{
    ComponentA,
    ComponentB
  },
  methods:{
    changeHandle(){
      this.tabComponent = this.tabComponent == "ComponentA"?"ComponentB":"ComponentA"
    }
  }
}
</script>
<style>

</style>

组件保持存活

  • 切换时会卸载组件
<template>
  <KeepAlive>
    <component :is="tabComponent"></component>
  </KeepAlive>
  
  <button @click="changeHandle">切换组件</button>
</template>

<script>
import ComponentA from './components/ComponentA.vue'
import ComponentB from './components/ComponentB.vue'
export default{
  data(){
    return{
      tabComponent: "ComponentA"
    }
  },
  components:{
    ComponentA,
    ComponentB
  },
  methods:{
    changeHandle(){
      this.tabComponent = this.tabComponent == "ComponentA"?"ComponentB":"ComponentA"
    }
  }
}
</script>
<style>

</style>
<template>
    <h3>ComponentA</h3>
    <p>{{ message }}</p>
    <button @click="updateHandle">更新数据</button>
</template>

<script>
export default{
    beforeUnmount(){
        console.log("组件卸载前")
    },
    unmounted(){
        console.log("组件卸载后")
    },
    data(){
        return{
            message:"老数据"
        }
    },
    methods:{
        updateHandle(){
            this.message = "新数据"
        }
    }
}
</script>
<template>
    <h3>ComponentB</h3>
</template>

异步组件

  • 在第一次进入网页时,没显示出来的网页先不加载,等显示出来后再加载
<template>
  <KeepAlive>
    <component :is="tabComponent"></component>
  </KeepAlive>
  
  <button @click="changeHandle">切换组件</button>
</template>

<script>
import { defineAsyncComponent } from 'vue'
import ComponentA from './components/ComponentA.vue'
// import ComponentB from './components/ComponentB.vue'
const ComponentB = defineAsyncComponent(()=>
  import("./components/ComponentB.vue")
)
export default{
  data(){
    return{
      tabComponent: "ComponentA"
    }
  },
  components:{
    ComponentA,
    ComponentB
  },
  methods:{
    changeHandle(){
      this.tabComponent = this.tabComponent == "ComponentA"?"ComponentB":"ComponentA"
    }
  }
}
</script>
<style>

</style>

依赖注入

  • 父组件作为依赖提供者,无论孩子有多深,都能用依赖获取数据。
  • provide 和 inject
  • 只能由上到下,不能反向
  • 可以在整个应用提供
    在这里插入图片描述
  • 爷爷
<template>
  <h3>祖宗</h3>
  <Father />
</template>

<script>
import Father from './components/Father.vue'
export default{
  // provide:{
  //   message:"爷爷的财产"
  // },
  data(){
    return{
      message:"爷爷的财产"
    }
  },
  provide(){
    return{
      message:this.message
    }
  },
  components:{
    Father
  }
}
</script>
<style>

</style>
  • 父亲
<template>
    <h3>父亲</h3>
    <Son />
  </template>
  
  <script>
  import Son from './Son.vue'
  export default{
    props:{
        title:{
            type:String
        }
    },
    components:{
        Son
    }
  }
  </script>
  
  • 孙子
<template>
    <h3>孩子</h3>
    <p>{{ fullMessage }}</p>
  </template>
  
  <script>
  export default{
    props:{
        title:{
            type:String
        }
    },
    inject:["message"],
    data(){
        return{
            fullMessage:this.message
        }
    }
  }
  </script>
  
  
  • 全局数据
import { createApp } from 'vue'
import App from './App.vue'


const app = createApp(App)
app.provide("golabData","我是全局数据")
app.mount("#app")

Vue应用

  • src/assets:资源文件夹
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <link rel="icon" href="/favicon.ico">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Vite App</title>
  </head>
  <body>
    <div id="app"></div>
    <script type="module" src="/src/main.js"></script>
  </body>
</html>

import { createApp } from 'vue'
import App from './App.vue'


const app = createApp(App)

app.mount("#app")

路由

  • cnpm install --save vue-router@4
  • App.vue
<template>
  <router-link to="/home">首页</router-link>
  <router-link to="/blog">博客</router-link>
  <router-view></router-view>
</template>

<script>
export default{
  name:'App'
}
</script>
<style>

</style>
  • router.js
import {createRouter,createWebHashHistory} from "vue-router"
import Home from "./components/Home.vue"
import Blog from "./components/Blog.vue"
const router = createRouter({
  history:  createWebHashHistory(),
  routes:[
    {
        path:"/home",
        component:Home
    },
    {
        path:"/blog",
        component:Blog
    }
  ]
})

export default router;
  • main.js
import { createApp } from 'vue'
import App from './App.vue'
import router from './router.js'

const app = createApp(App)
app.use(router);
app.mount("#app")

  • Home.vue,Blog.vue 略

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1164874.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

汽车标定技术(一):XCP概述

目录 1.汽车标定概述 2.XCP协议由来及版本介绍 3.XCP技术通览 3.1 XCP上下机通信模型 3.2 XCP指令集 3.2.1 XCP帧结构定义 3.2.2 标准指令集 3.2.3 标定指令集 3.2.4 页切换指令集 3.2.5 数据采集指令集 3.2.6 刷写指令集 3.3 ECU描述文件(A2L)概述 3.3.1 标定上位…

无限上下文,多级内存管理!突破ChatGPT等大语言模型上下文限制

目前&#xff0c;ChatGPT、Llama 2、文心一言等主流大语言模型&#xff0c;因技术架构的问题上下文输入一直受到限制&#xff0c;即便是Claude 最多只支持10万token输入&#xff0c;这对于解读上百页报告、书籍、论文来说非常不方便。 为了解决这一难题&#xff0c;加州伯克利…

物联网AI MicroPython传感器学习 之 QMC5883指南针罗盘传感器

学物联网&#xff0c;来万物简单IoT物联网&#xff01;&#xff01; 一、产品简介 QMC5883是一款表面贴装的集成了信号处理电路的三轴磁性传感器&#xff0c;应用场景主要包括罗盘、导航、无人机、机器人和手持设备等一些高精度的场合。 引脚定义 VCC&#xff1a;3V3&#…

【Java 进阶篇】Java ServletContext详解:获取MIME类型

MIME&#xff08;Multipurpose Internet Mail Extensions&#xff09;类型是一种标识文件类型的文本标签&#xff0c;通常用于指示浏览器如何处理Web服务器返回的文件。在Java Web应用程序中&#xff0c;ServletContext对象提供了一种方便的方法来获取文件的MIME类型。本篇博客…

【实战Flask API项目指南】之五 RESTful API设计

实战Flask API项目指南之 RESTful API设计 本系列文章将带你深入探索实战Flask API项目指南&#xff0c;通过跟随小菜的学习之旅&#xff0c;你将逐步掌握 Flask 在实际项目中的应用。让我们一起踏上这个精彩的学习之旅吧&#xff01; 前言 当小菜踏入Flask后端开发的世界时…

Redis-命令操作Redis

&#x1f3ac; 艳艳耶✌️&#xff1a;个人主页 &#x1f525; 个人专栏 &#xff1a;《Spring与Mybatis集成整合》《Vue.js使用》 ⛺️ 越努力 &#xff0c;越幸运。 1.Redis简介 1.1.什么是Redis Redis是一个开源&#xff08;BSD许可&#xff09;&#xff0c;内存存储的数据…

费用预算管理系统

费用预算管理系统 1. 模块概述 《费用管理》以企业费用管理为核心&#xff0c;围绕费用支出审批流程&#xff0c;从费用发生前的事前申请&#xff0c;报销单据审批、付款单据审批&#xff0c;再到出纳付款、会计记账等所有工作流程都在系统中全员、协同完成&#xff1b;并且能…

el-table中的el-input标签修改值,但界面未更新,解决方法

el-table中的el-input标签修改值&#xff0c;界面未更新 在el-table中的el-input里面写的change事件根本不触发&#xff0c;都不打印&#xff0c;试了网络上各种方法都没用 然后换成input事件&#xff0c;input事件会触发&#xff0c;但界面也未更新。我在触发事件的时候&…

微信小程序之开发工具介绍

一、微信小程序开发工具下载 微信小程序开发工具下载可以参考这篇博客《微信小程序开发者工具下载-CSDN博客》 二、开发工具组成部分 如下图所示&#xff0c;开发者工具主要由菜单栏、工具栏、模拟器、编辑器和调试器 5 个部分组成。。 1、菜单栏 菜单栏中主要包括项目、文…

听GPT 讲Rust源代码--library/std(13)

题图来自 Decoding Rust: Everything You Need to Know About the Programming Language[1] File: rust/library/std/src/os/horizon/raw.rs 在Rust源代码中&#xff0c;rust/library/std/src/os/horizon/raw.rs这个文件的作用是为Rust的标准库提供与Horizon操作系统相关的原始…

STM32HAL-完全解耦面向对象思维的架构-时间轮片法使用(timeslice)

目录 概述 一、开发环境 二、STM32CubeMx配置 三、编码 四、运行结果 五、代码解释 六、总结 概述 timeslice是一个时间片轮询框架&#xff0c;完全解耦的时间片轮询框架&#xff0c;非常适合裸机单片机引用。接下来将该框架移植到stm32单片机运行&#xff0c;单片机…

王道计算机网络

一、计算机网络概述 (一)计算机网络基本概念 计算机网络的定义、组成与功能 定义&#xff1a;以能够相互共享资源的方式互连起来的自治计算机系统的集合。 目的&#xff1a;资源共享&#xff0c; 组成单元&#xff1a;自治、互不影响的计算机 网络协议 从不同角度计算机网络…

【Python入门二】安装第三方库(包)

安装第三方库/包 1 使用pip安装2 使用PyCharm软件安装3 离线安装&#xff0c;使用whl文件安装参考 在Python中&#xff0c;有多种安装第三方库的方法&#xff0c;下面是一些常用的方法&#xff1a; 1 使用pip安装 pip是Python中最常用的包管理工具&#xff0c;也是最常用的在线…

PASCAL VOC 格式

文章目录 ImageSets 文件夹Main 文件夹:Segmentation 文件夹:Layout 文件夹:Action 文件夹: Annotations 文件夹主要标签&#xff1a;物体标签&#xff1a; SegmentationClass 文件夹SegmentationObject 文件夹 PASCAL VOC&#xff08;Visual Object Classes&#xff09;是一个…

计算流体动力学(CFD)软件

CFD&#xff0c;英语全称 (Computational Fluid Dynamics&#xff09;&#xff0c;即计算流体动力学。CFD 是近代流体力学&#xff0c;数值数学和计算机科学结合的产物&#xff0c;是一门具有强大生命力的交叉科学。它是将流体力学的控制方程中积分、微分项近似地表示为离散的代…

ardupilot开发 --- 代码解析 篇

0. 前言 根据SITL的断点调试和自己阅读代码的一些理解&#xff0c;写一点自己的注释&#xff0c;有什么不恰当的地方请各位读者不吝赐教。 1. GCS::update_send 线程 主动向MavLink system发送消息包。 1.1 不断向地面站发送飞机状态数据 msg_attitude: msg_location: n…

MYSQL 多表联查详解

目录 一、一个案例引发的多表连接 二、笛卡尔积的错误和与正确的多表查询 2.1、笛卡尔积错误展示 2.2、笛卡尔积解决方法 2.3、练习 三、多表查询分类 3.1、等值连接 vs 非等值连接 3.2、自连接 vs 非自连接 3.3、内连接 vs 外连接 内连接&#xff08;inner join&…

基于FPGA的图像RGB转CMYK实现,包含testbench和MATLAB辅助验证程序

目录 1.算法运行效果图预览 2.算法运行软件版本 3.部分核心程序 4.算法理论概述 4.1、RGB转CMYK的原理 4.2、基于FPGA的实现方法 5.算法完整程序工程 1.算法运行效果图预览 将仿真结果导入到matlab中&#xff0c;得到如下对比结果&#xff1a; 2.算法运行软件版本 matl…

C++虚函数产生的多态

C虚函数产生的多态 1、先看下面代码&#xff0c;参考施雷老师课堂笔记 #include<iostream> #include<vector> #include <algorithm> #include <functional> using namespace std;/* 虚函数&#xff0c;静态绑定和动态绑定覆盖&#xff1a; 基类和派生…

Vue3 实现 clipboard 复制功能

一个很小的交互功能&#xff0c;网上搜了一下有一个 vue3-clipboard 直接支持vue3&#xff0c;到github仓库看了下&#xff0c;原作者已经不维护这个项目了&#xff1a; 推荐使用 vueuse 自带的 useclipboard 功能&#xff0c;由 vue 团队维护&#xff0c;稳定性基本没问题 官…