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

这篇具有很好参考价值的文章主要介绍了Vue3入门指南:零基础小白也能轻松理解的学习笔记。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

创建项目

  • 配置 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>

组件嵌套关系

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

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
    Vue3入门指南:零基础小白也能轻松理解的学习笔记,前端,前端
<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

  • 子元素数据传给父插槽

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

<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>

具名插槽传递数据

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

<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>

组件的声明周期

Vue3入门指南:零基础小白也能轻松理解的学习笔记,前端,前端文章来源地址https://www.toymoban.com/news/detail-740285.html

  • 创建:创建后系统才开始初始化数据
  • 渲染:显示
  • 更新:用户操作导致改变,渲染和显示
  • 销毁
<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
  • 只能由上到下,不能反向
  • 可以在整个应用提供
    Vue3入门指南:零基础小白也能轻松理解的学习笔记,前端,前端
  • 爷爷
<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 略

mitt 全局传递数据

pinia 全局状态管理工具

到了这里,关于Vue3入门指南:零基础小白也能轻松理解的学习笔记的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • 自然语言处理2——轻松入门情感分析 - Python实战指南

    情感分析是一项强大的数据分析工具,它能够帮助我们深入理解文本背后的情感色彩。在企业和社交媒体中,情感分析被广泛应用,以洞察用户的情感倾向,改善产品和服务,提升用户体验。本篇博客将带您轻松入门情感分析,使用Python中常见的情感分析库进行实战指南。

    2024年02月03日
    浏览(42)
  • 爬虫入门指南(7):使用Selenium和BeautifulSoup爬取豆瓣电影Top250实例讲解【爬虫小白必看】

    在本篇博客中,我们将使用 Python 的 Selenium 和 BeautifulSoup 库来实现一个简单的网页爬虫,目的是爬取豆瓣电影TOP250的数据,并将结果保存到Excel文件中。 Selenium 是一个自动化测试工具,可以模拟用户在浏览器中的交互操作。我们将使用 Selenium 来打开网页、获取网页源码。 B

    2024年02月12日
    浏览(35)
  • Java 零基础入门学习(小白也能看懂!)

    📚博客主页:爱敲代码的小杨. ✨专栏:《Java SE语法》 ❤️感谢大家点赞👍🏻收藏⭐评论✍🏻,您的三连就是我持续更新的动力❤️ 1.1.1什么是 Java Java是一种优秀的程序设计语言 ,它具有令人赏心悦目的语法和易于理解的语义。 不仅如此, Java还是一个有一系列计算机软

    2024年01月19日
    浏览(33)
  • Oracle 基础入门指南

      Oracle是一款由美国Oracle公司开发的关系型数据库管理系统。它支持SQL查询语言,并提供了丰富的功能和工具,用于管理大规模数据存储、处理和访问。Oracle被广泛应用于企业级应用中,包括金融、电信、零售等各行各业。 要开始学习Oracle,首先需要在计算机上安装Oracle数据

    2024年02月19日
    浏览(26)
  • 大数据基础技能入门指南

    本文介绍了数据工作中数据基础和复杂数据查询两个基础技能。 背景 当下,不管是业务升级迭代项目,还是体验优化项目,对于数据的需求都越来越大。数据需求主要集中在以下几个方面: 项目数据看板搭建:特别是一些AB实验的看板,能直观呈现项目的核心数据变化 数据

    2024年02月05日
    浏览(35)
  • 计算机视觉基础入门指南

            计算机视觉是一门研究如何使计算机能够“看”和理解图像或视频的学科。随着人工智能的快速发展,计算机视觉在各个领域的应用越来越广泛。本文将为您介绍计算机视觉的基本概念、应用领域以及学习路径,帮助您快速入门这一领域。 图像处理:对图像进行预处

    2024年04月11日
    浏览(36)
  • HarmonyOS云开发基础认证题目记录——包括第一期:Serverless基础、第二期:快速构建用户认证系统、第三期:云函数入门指南、第四期:云数据库入门指南、第五期:云存储入门指南。

    1. 【判断题】  应用架构的演进依次经历了微服务架构、单体架构、Serverless架构等阶段。 错误 2. 【判断题】  认证服务手机号码登录需要填写国家码。 正确 3. 【判断题】  认证服务在绑定微信账号后就不能再绑定QQ账号了。 错误 4. 【判断题】  云函数可以根据函数的实际

    2024年02月05日
    浏览(67)
  • 后端扫盲系列 - vue入门指南

    组件化:用户界面分解为可重用的组件,这些组件可以使开发的页面更加模块化和可维护= 双向数据绑定:vue提供了一种轻松绑定数据和DOM元素之间的机制,意味着数据发送变化时,视图会自动更新,反之亦然 虚拟DOM:vue使用虚拟DOM来最小化实际DOM更新的次数,从而提高性能

    2024年02月19日
    浏览(24)
  • AI绘图-Midjourney零基础入门指南

    Midjourney 是除 Disco Difussion 和 Dall·E 2 之外又一个比较优秀的 AI 图像生成器,它综合能力全面,虽然图像的精准度及艺术性不及 Disco Difussion,但易上手程度比 Disco Difussion 好很多,图像生成速度极快 1 分钟内出 4 张图,国外很多艺术家都使用 Midjourney 生成自己想要图像作为创

    2024年02月04日
    浏览(31)
  • 【三十天精通 Vue 3】 第一天 Vue 3入门指南

    ✅创作者:陈书予 🎉个人主页:陈书予的个人主页 🍁陈书予的个人社区,欢迎你的加入: 陈书予的社区 🌟专栏地址: 三十天精通 Vue 3

    2024年02月11日
    浏览(30)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包