当前位置: 首页>后端>正文

vue2 与vue3

1.生命周期

vue3 Composition API,vue2 Option Api

vue2 与vue3,第1张

选项式api中

beforeDestroy 改名为 beforeUnmount
destroyed 改名为unmounted

volar 开发vue3需要禁用vetur,开发vue2禁用volar

2.组合式api书写方式

<script>
import HelloWorld from './components/HelloWorld.vue'
import { ref } from 'vue'
export default {
  name: 'App',
  components: {
    HelloWorld
  },
  props: {
    title: String
  },
  setup(props,context) { 
    console.log(props.title);
    console.log(context);
    const num = ref(0)
    const show = () => {
      console.log(111);
    }
    return {
      num,
      show
    }
  }

}
</script>

3.组合式api语法糖写法

<template>
    <div>{{ aa }}</div>
    <HelloWorld/>
</template>
<script setup lang='ts'>
import { ref } from 'vue'
import HelloWorld from '@/components/HelloWorld.vue'
const aa = ref(1)

</script>

变量定义

ref reactive
1.ref ,取值需要使用.value

//ref用法
const aa = ref(1)
aa.value = 2

2.reactive,取值不需要.value,只支持引用类型 Array,Object,Map,Set等,不能直接赋值,会失去响应式

let list = reactive({
  name: '11',
  age: 15
})
const change = () => {
  Object.assign(list,{
  name: '121',
  age: 15
})
  console.log(list);
}

watch监听 watchEffext监听

区别:watch监听=>第一次页面展示的时候不会执行,只有数据变化的时候才会执行(设置immediate true时可以变为非惰性,页面首次加载就会执行)
watchEffext监听=>立即执行,没有惰性,页面的首次加载就会执行,无法获取到原值,只能得到变化后的值
属性:flush

vue2 与vue3,第2张
const name = ref(111)
watch(name,(newVal)=>{
  console.log(newVal);
},{
  deep:true,
  immediate:true,
  flush:'pre'
})

组件传递

接收:defineProps,
发送:defineEmits(['update:modelValue']),defineEmits(['on-click'])

pinia

安装 npm install pinia
修改state的值

const changeState = () => {
//第一种
  store.count++
//第二种
  store.$patch({
    count:222
  })
//第三种,必须全部修改,有一个没修改就报错
store.$state = {
    count: 333
  }
  console.log(store.count);
}

state解构,因为pinia解构不具有响应式,需要使用storeToRefs包裹

import { useStore } from './store/store.ts'
import { storeToRefs } from "pinia";
let {count} =storeToRefs(useStore())
const changeState = () => {
  count.value++
  console.log(count.value);
}

调用actions

import { defineStore } from "pinia";
export const useStore = defineStore('use',{
  state: () => {
    return {
        count:1
    };
  },
  getters:{
getName(){
      return this.count=2;
    }
},
  actions:{
    setCount(){
      this.count=1243
  }
  }
});
<h1>{{ store.getName }}</h1>
store.setCount()

api
$reset() 恢复初始值
$subscribe 只要state的值变化就会触发

store.$subscribe((args, state) => {
  console.log(args);
  console.log(state);
}, {
  detached: true,
  deep: true,
  flush: 'post'
})

$onAction 只要调用actions就会调用,true是组件被销毁后还想监听

store.$onAction((args)=>{
args.after(()=>{})
  console.log(args);
  
},true)

https://www.xamrdz.com/backend/3r91921146.html

相关文章: