vue3学习(二)

发布于:2024-05-30 ⋅ 阅读:(178) ⋅ 点赞:(0)

前言

       上一篇分享了vue的基础指令,这篇记录下vue3的核心内容,也是自己的学习笔记,可能有些核心还不全,大佬请略过。


一、核心内容

       分享这个之前,先声明下,我这里是用的脚手架的写法,分享的讲解截图是vue3js暴露的写法,刚好可以对比理解,我也是这样的,学习的是暴露的写法,自己code的示例是脚手架的写法,与大家共同进步。
先上我自己code的示例代码:(还是接着之前webstrom创建的项目code)
App.vue

<template>
  <HelloWorld v-bind:msg="msg"/>

  <!-- v-model更多用法 -->
  <input type="text" v-model.number.lazy="inNum">

  <!-- 计算属性 -->
  <p ref="msgTitle">msg:{{ msg }}</p>

  <p>reversedMsg:{{ reversedMsg }}</p>

  <p>doubleNum:{{ doubleNum }}</p>

  <!-- watch监听 -->
  <ul>
    <li>name:{{ user.name }}</li>
    <li>age:{{ user.age }}</li>
    <li>school{{ user.school }}</li>
  </ul>
  <input type="text" @change="changeUserName($event.target.value)" v-model="user.name">

  <!-- 当前实例属性 -->
  <p>
    <span ref="aaa">aaa ref</span>
  </p>

  <button @click="changeMsg()">修改你好</button>

</template>

<script setup>
import {ref, computed, watch, getCurrentInstance, nextTick} from 'vue'
import HelloWorld from './components/HelloWorld.vue'

// ref创建响应式数据
const msg = ref('Welcome to Your Vue.js App')
const inNum = ref(0)

const user = ref({
  name: ref('John'),
  age: ref(25),
  school: ref('MIT')
})

// methods
function changeUserName(newName) {
  user.value.name = newName;
}
function changeMsg(){
  console.log("---修改msg---");
  this.msg = "你好";
  //直接proxy.$refs.msgTitle可能慧出现页面还没有渲染完的情况
  //console.log("----",proxy.$refs.msgTitle)

  //使用nextTick,迭代页面渲染完,再取里面的内容
  proxy.$nextTick(function (){
    console.log("--msgRefHtml",proxy.$refs.msgTitle)
  })
}

// computed
const reversedMsg = computed(() => {
  return msg.value.toUpperCase().split(" ").reverse().join(" ");
})

const doubleNum = computed(() => {
  return inNum.value * 2;
})

// watch
watch(inNum.value, (newVal, oldVal) => {
  console.log('newVal:', newVal, 'oldVal:', oldVal);
})

watch(user.value, (newUser) => {
  console.log('new name:', newUser.name);
}, {deep: true, immediate: true})

//vue3.2.0新增getCurrentInstance,获取当前实例
const dint = getCurrentInstance();
console.log(dint)

//这种方式只能在开发环境下使用,生产环境下的ctx将访问不到
const {ctx} = getCurrentInstance();
console.log(ctx.$refs)

//此方法在开发环境以及生产环境下都能放到组件上下文对象(推荐)
const {proxy} = getCurrentInstance();
console.log(proxy.$refs)

//nextTick
nextTick(() =>{
  //var msgTitleRef = proxy.$refs.msgTitle;
  var msgRefHtml = proxy.$refs.msgTitle;
  console.log("--msgRefHtml",msgRefHtml)
})


</script>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

计算属性

在这里插入图片描述

监视器

在这里插入图片描述

实例方法

在这里插入图片描述

模版

在这里插入图片描述

生命周期

在这里插入图片描述
注意:
beforeCreate并不是字面意思上的在创建前,具体还是看下vue官网给出的生命周期的解释图:

在这里插入图片描述

二、脚手架写法注意

       code的示例代码,大家有没有注意看<script后面跟了一个setup,这个实际就是与生命周期的steup(组合式API)对应的。


总结

  • vuejs暴露的写法基本会html,js就可以上手干了
  • 脚手架写法才是新阶段的开始
           就是笔记备忘,希望跟大家一起进步,uping!

网站公告

今日签到

点亮在社区的每一天
去签到