想知道Vue3與Vue2的區別?五千字教程助你快速上手Vue3!

来源:https://www.cnblogs.com/zdsdididi/archive/2022/06/21/16396088.html
-Advertisement-
Play Games

從Vue3發佈以來,我就一直對其非常感興趣,就一直想著將其投入公司的生產中,但是開始考慮到很多不確定性就暫時對一些很小的功能進行一些嘗試;慢慢的發現組合式Api的形式非常適合開發(個人感覺),尤其是Vue3.2推出了setup語法糖後直呼真香。後面公司的新項目幾乎全部採用了Vue3了。使用Vue3開 ...


從Vue3發佈以來,我就一直對其非常感興趣,就一直想著將其投入公司的生產中,但是開始考慮到很多不確定性就暫時對一些很小的功能進行一些嘗試;慢慢的發現組合式Api的形式非常適合開發(個人感覺),尤其是Vue3.2推出了setup語法糖後直呼真香。後面公司的新項目幾乎全部採用了Vue3了。使用Vue3開發也將近大半年了,所以寫了這篇文章對Vue2和Vue3做了一個對比總結,一是為了對這段時間使用Vue3開發做些記錄,二是為了幫助更多的小伙伴更快的上手Vue3。

本篇文章主要採用選項式Api,組合式Api,setup語法糖實現它們直接的差異

選項式Api與組合式Api

首先實現一個同樣的邏輯(點擊切換頁面數據)看一下它們直接的區別

  • 選項式Api
<template>
<div @click="changeMsg">{{msg}}</div>
</template>
<script>
export default  {
  data(){
    return {
     msg:'hello world'
    }
  },
  methods:{
    changeMsg(){
      this.msg = 'hello juejin'
    }
  }
}
</script>
  • 組合式Api
<template>
 <div @click="changeMsg">{{msg}}</div>
</template>

<script>
import { ref,defineComponent } from "vue";
export default defineComponent({
setup() {
    const msg = ref('hello world')
    const changeMsg = ()=>{
      msg.value = 'hello juejin'
    }
return {
  msg,
  changeMsg
};
},
});
</script>
  • setup 語法糖
<template>
  <div @click="changeMsg">{{ msg }}</div>
</template>

<script setup>
import { ref } from "vue";

const msg = ref('hello world')
const changeMsg = () => {
  msg.value = 'hello juejin'
}
</script>

總結

選項式Api是將data和methods包括後面的watch,computed等分開管理,而組合式Api則是將相關邏輯放到了一起(類似於原生js開發)。

setup語法糖則可以讓變數方法不用再寫return,後面的組件甚至是自定義指令也可以在我們的template中自動獲得。

ref 和 reactive

我們都知道在組合式api中,data函數中的數據都具有響應式,頁面會隨著data中的數據變化而變化,而組合式api中不存在data函數該如何呢?所以為瞭解決這個問題Vue3引入了ref和reactive函數來將使得變數成為響應式的數據

  • 組合式Api
<script>
import { ref,reactive,defineComponent } from "vue";
export default defineComponent({
setup() {
let msg = ref('hello world')
let obj = reactive({
    name:'juejin',
    age:3
})
const changeData = () => {
  msg.value = 'hello juejin'
  obj.name = 'hello world'
}
return {
msg,
obj,
changeData
};
},
});
</script>
  • setup語法糖
<script setup>
import { ref,reactive } from "vue";
let msg = ref('hello world')
let obj = reactive({
    name:'juejin',
    age:3
})
const changeData = () => {
  msg.value = 'hello juejin'
  obj.name = 'hello world'
}
</script>

總結

使用ref的時候在js中取值的時候需要加上.value。

reactive更推薦去定義複雜的數據類型 ref 更推薦定義基本類型

生命周期

下表包含:Vue2和Vue3生命周期的差異

Vue2(選項式API) Vue3(setup) 描述
beforeCreate - 實例創建前
created - 實例創建後
beforeMount onBeforeMount DOM掛載前調用
mounted onMounted DOM掛載完成調用
beforeUpdate onBeforeUpdate 數據更新之前被調用
updated onUpdated 數據更新之後被調用
beforeDestroy onBeforeUnmount 組件銷毀前調用
destroyed onUnmounted 組件銷毀完成調用

舉個常用的onBeforeMount的例子

  • 選項式Api
<script>
export default  {
  mounted(){
    console.log('掛載完成')
  }
}
</script>
  • 組合式Api
<script>
import { onMounted,defineComponent } from "vue";
export default defineComponent({
setup() {
onMounted(()=>{
  console.log('掛載完成')
})
return {
onMounted
};
},
});
</script>
  • setup語法糖
<script setup>
import { onMounted } from "vue";
onMounted(()=>{
  console.log('掛載完成')
})
</script>

從上面可以看出Vue3中的組合式API採用hook函數引入生命周期;其實不止生命周期採用hook函數引入,像watch、computed、路由守衛等都是採用hook函數實現

總結

Vue3中的生命周期相對於Vue2做了一些調整,命名上發生了一些變化並且移除了beforeCreate和created,因為setup是圍繞beforeCreate和created生命周期鉤子運行的,所以不再需要它們。

生命周期採用hook函數引入

watch和computed

  • 選項式API
<template>
  <div>{{ addSum }}</div>
</template>
<script>
export default {
  data() {
    return {
      a: 1,
      b: 2
    }
  },
  computed: {
    addSum() {
      return this.a + this.b
    }
  },
  watch:{
    a(newValue, oldValue){
      console.log(`a從${oldValue}變成了${newValue}`)
    }
  }
}
</script>
  • 組合式Api
<template>
  <div>{{addSum}}</div>
</template>
<script>
import { computed, ref, watch, defineComponent } from "vue";
export default defineComponent({
  setup() {
    const a = ref(1)
    const b = ref(2)
    let addSum = computed(() => {
      return a.value+b.value
    })
    watch(a, (newValue, oldValue) => {
     console.log(`a從${oldValue}變成了${newValue}`)
    })
    return {
      addSum
    };
  },
});
</script>
  • setup語法糖
<template>
  <div>{{ addSum }}</div>
</template>
<script setup>
import { computed, ref, watch } from "vue";
const a = ref(1)
const b = ref(2)
let addSum = computed(() => {
  return a.value + b.value
})
watch(a, (newValue, oldValue) => {
  console.log(`a從${oldValue}變成了${newValue}`)
})
</script>

Vue3中除了watch,還引入了副作用監聽函數watchEffect,用過之後我發現它和React中的useEffect很像,只不過watchEffect不需要傳入依賴項。

那麼什麼是watchEffect呢?

watchEffect它會立即執行傳入的一個函數,同時響應式追蹤其依賴,併在其依賴變更時重新運行該函數。

比如這段代碼

<template>
  <div>{{ watchTarget }}</div>
</template>
<script setup>
import { watchEffect,ref } from "vue";
const watchTarget = ref(0)
watchEffect(()=>{
  console.log(watchTarget.value)
})
setInterval(()=>{
  watchTarget.value++
},1000)
</script>

首先剛進入頁面就會執行watchEffect中的函數列印出:0,隨著定時器的運行,watchEffect監聽到依賴數據的變化回調函數每隔一秒就會執行一次

總結

computed和watch所依賴的數據必須是響應式的。Vue3引入了watchEffect,watchEffect 相當於將 watch 的依賴源和回調函數合併,當任何你有用到的響應式依賴更新時,該回調函數便會重新執行。不同於 watch的是watchEffect的回調函數會被立即執行,即({ immediate: true })

組件通信

Vue中組件通信方式有很多,其中選項式API和組合式API實現起來會有很多差異;這裡將介紹如下組件通信方式:

方式 Vue2 Vue3
父傳子 props props
子傳父 $emit emits
父傳子 $attrs attrs
子傳父 $listeners 無(合併到 attrs方式)
父傳子 provide provide
子傳父 inject inject
子組件訪問父組件 $parent
父組件訪問子組件 $children
父組件訪問子組件 $ref expose&ref
兄弟傳值 EventBus mitt

props

props是組件通信中最常用的通信方式之一。父組件通過v-bind傳入,子組件通過props接收,下麵是它的三種實現方式

  • 選項式API
//父組件

<template>
  <div>
    <Child :msg="parentMsg" />
  </div>
</template>
<script>
import Child from './Child'
export default {
  components:{
    Child
  },
  data() {
    return {
      parentMsg: '父組件信息'
    }
  }
}
</script>


//子組件

<template>
  <div>
    {{msg}}
  </div>
</template>
<script>
export default {
  props:['msg']
}
</script>

  • 組合式Api
//父組件

<template>
  <div>
    <Child :msg="parentMsg" />
  </div>
</template>
<script>
import { ref,defineComponent } from 'vue'
import Child from './Child.vue'
export default defineComponent({
  components:{
    Child
  },
  setup() {
    const parentMsg = ref('父組件信息')
    return {
      parentMsg
    };
  },
});
</script>

//子組件

<template>
    <div>
        {{ parentMsg }}
    </div>
</template>
<script>
import { defineComponent,toRef } from "vue";
export default defineComponent({
    props: ["msg"],// 如果這行不寫,下麵就接收不到
    setup(props) {
        console.log(props.msg) //父組件信息
        let parentMsg = toRef(props, 'msg')
        return {
            parentMsg
        };
    },
});
</script>

  • setup語法糖

//父組件

<template>
  <div>
    <Child :msg="parentMsg" />
  </div>
</template>
<script setup>
import { ref } from 'vue'
import Child from './Child.vue'
const parentMsg = ref('父組件信息')
</script>

//子組件

<template>
    <div>
        {{ parentMsg }}
    </div>
</template>
<script setup>
import { toRef, defineProps } from "vue";
const props = defineProps(["msg"]);
console.log(props.msg) //父組件信息
let parentMsg = toRef(props, 'msg')
</script>

註意

props中數據流是單項的,即子組件不可改變父組件傳來的值

在組合式API中,如果想在子組件中用其它變數接收props的值時需要使用toRef將props中的屬性轉為響應式。

emit

子組件可以通過emit發佈一個事件並傳遞一些參數,父組件通過v-onj進行這個事件的監聽

  • 選項式API

//父組件

<template>
  <div>
    <Child @sendMsg="getFromChild" />
  </div>
</template>
<script>
import Child from './Child'
export default {
  components:{
    Child
  },
  methods: {
    getFromChild(val) {
      console.log(val) //我是子組件數據
    }
  }
}
</script>

// 子組件

<template>
  <div>
    <button @click="sendFun">send</button>
  </div>
</template>
<script>
export default {
  methods:{
    sendFun(){
      this.$emit('sendMsg','我是子組件數據')
    }
  }
}
</script>

  • 組合式Api

//父組件

<template>
  <div>
    <Child @sendMsg="getFromChild" />
  </div>
</template>
<script>
import Child from './Child'
import { defineComponent } from "vue";
export default defineComponent({
  components: {
    Child
  },
  setup() {
    const getFromChild = (val) => {
      console.log(val) //我是子組件數據
    }
    return {
      getFromChild
    };
  },
});
</script>

//子組件

<template>
    <div>
        <button @click="sendFun">send</button>
    </div>
</template>

<script>
import { defineComponent } from "vue";
export default defineComponent({
    emits: ['sendMsg'],
    setup(props, ctx) {
        const sendFun = () => {
            ctx.emit('sendMsg', '我是子組件數據')
        }
        return {
            sendFun
        };
    },
});
</script>

  • setup語法糖

//父組件

<template>
  <div>
    <Child @sendMsg="getFromChild" />
  </div>
</template>
<script setup>
import Child from './Child'
const getFromChild = (val) => {
      console.log(val) //我是子組件數據
    }
</script>

//子組件

<template>
    <div>
        <button @click="sendFun">send</button>
    </div>
</template>
<script setup>
import { defineEmits } from "vue";
const emits = defineEmits(['sendMsg'])
const sendFun = () => {
    emits('sendMsg', '我是子組件數據')
}
</script>

attrs和listeners

子組件使用$attrs可以獲得父組件除了props傳遞的屬性和特性綁定屬性 (class和 style)之外的所有屬性。

子組件使用$listeners可以獲得父組件(不含.native修飾器的)所有v-on事件監聽器,在Vue3中已經不再使用;但是Vue3中的attrs不僅可以獲得父組件傳來的屬性也可以獲得父組件v-on事件監聽器

  • 選項式API

//父組件

<template>
  <div>
    <Child @parentFun="parentFun" :msg1="msg1" :msg2="msg2"  />
  </div>
</template>
<script>
import Child from './Child'
export default {
  components:{
    Child
  },
  data(){
    return {
      msg1:'子組件msg1',
      msg2:'子組件msg2'
    }
  },
  methods: {
    parentFun(val) {
      console.log(`父組件方法被調用,獲得子組件傳值:${val}`)
    }
  }
}
</script>

//子組件

<template>
  <div>
    <button @click="getParentFun">調用父組件方法</button>
  </div>
</template>
<script>
export default {
  methods:{
    getParentFun(){
      this.$listeners.parentFun('我是子組件數據')
    }
  },
  created(){
    //獲取父組件中所有綁定屬性
    console.log(this.$attrs)  //{"msg1": "子組件msg1","msg2": "子組件msg2"}
    //獲取父組件中所有綁定方法    
    console.log(this.$listeners) //{parentFun:f}
  }
}
</script>

  • 組合式API

//父組件

<template>
  <div>
    <Child @parentFun="parentFun" :msg1="msg1" :msg2="msg2" />
  </div>
</template>
<script>
import Child from './Child'
import { defineComponent,ref } from "vue";
export default defineComponent({
  components: {
    Child
  },
  setup() {
    const msg1 = ref('子組件msg1')
    const msg2 = ref('子組件msg2')
    const parentFun = (val) => {
      console.log(`父組件方法被調用,獲得子組件傳值:${val}`)
    }
    return {
      parentFun,
      msg1,
      msg2
    };
  },
});
</script>

//子組件

<template>
    <div>
        <button @click="getParentFun">調用父組件方法</button>
    </div>
</template>
<script>
import { defineComponent } from "vue";
export default defineComponent({
    emits: ['sendMsg'],
    setup(props, ctx) {
        //獲取父組件方法和事件
        console.log(ctx.attrs) //Proxy {"msg1": "子組件msg1","msg2": "子組件msg2"}
        const getParentFun = () => {
            //調用父組件方法
            ctx.attrs.onParentFun('我是子組件數據')
        }
        return {
            getParentFun
        };
    },
});
</script>

  • setup語法糖

//父組件

<template>
  <div>
    <Child @parentFun="parentFun" :msg1="msg1" :msg2="msg2" />
  </div>
</template>
<script setup>
import Child from './Child'
import { ref } from "vue";
const msg1 = ref('子組件msg1')
const msg2 = ref('子組件msg2')
const parentFun = (val) => {
  console.log(`父組件方法被調用,獲得子組件傳值:${val}`)
}
</script>

//子組件

<template>
    <div>
        <button @click="getParentFun">調用父組件方法</button>
    </div>
</template>
<script setup>
import { useAttrs } from "vue";

const attrs = useAttrs()
//獲取父組件方法和事件
console.log(attrs) //Proxy {"msg1": "子組件msg1","msg2": "子組件msg2"}
const getParentFun = () => {
    //調用父組件方法
    attrs.onParentFun('我是子組件數據')
}
</script>

註意

Vue3中使用attrs調用父組件方法時,方法前需要加上on;如parentFun->onParentFun

provide/inject

provide:是一個對象,或者是一個返回對象的函數。裡面包含要給子孫後代屬性

inject:一個字元串數組,或者是一個對象。獲取父組件或更高層次的組件provide的值,既在任何後代組件都可以通過inject獲得

  • 選項式API

//父組件
<script>
import Child from './Child'
export default {
  components: {
    Child
  },
  data() {
    return {
      msg1: '子組件msg1',
      msg2: '子組件msg2'
    }
  },
  provide() {
    return {
      msg1: this.msg1,
      msg2: this.msg2
    }
  }
}
</script>

//子組件

<script>
export default {
  inject:['msg1','msg2'],
  created(){
    //獲取高層級提供的屬性
    console.log(this.msg1) //子組件msg1
    console.log(this.msg2) //子組件msg2
  }
}
</script>

  • 組合式API

//父組件

<script>
import Child from './Child'
import { ref, defineComponent,provide } from "vue";
export default defineComponent({
  components:{
    Child
  },
  setup() {
    const msg1 = ref('子組件msg1')
    const msg2 = ref('子組件msg2')
    provide("msg1", msg1)
    provide("msg2", msg2)
    return {
      
    }
  },
});
</script>

//子組件

<template>
    <div>
        <button @click="getParentFun">調用父組件方法</button>
    </div>
</template>
<script>
import { inject, defineComponent } from "vue";
export default defineComponent({
    setup() {
        console.log(inject('msg1').value) //子組件msg1
        console.log(inject('msg2').value) //子組件msg2
    },
});
</script>

  • setup語法糖

//父組件
<script setup>
import Child from './Child'
import { ref,provide } from "vue";
const msg1 = ref('子組件msg1')
const msg2 = ref('子組件msg2')
provide("msg1",msg1)
provide("msg2",msg2)
</script>

//子組件

<script setup>
import { inject } from "vue";
console.log(inject('msg1').value) //子組件msg1
console.log(inject('msg2').value) //子組件msg2
</script>

說明

provide/inject一般在深層組件嵌套中使用合適。一般在組件開發中用的居多。

parent/children

$parent: 子組件獲取父組件Vue實例,可以獲取父組件的屬性方法等

$children: 父組件獲取子組件Vue實例,是一個數組,是直接兒子的集合,但並不保證子組件的順序

  • Vue2
import Child from './Child'
export default {
  components: {
    Child
  },
  created(){
    console.log(this.$children) //[Child實例]
    console.log(this.$parent)//父組件實例
  }
}

註意
父組件獲取到的$children並不是響應式的

expose&ref

$refs可以直接獲取元素屬性,同時也可以直接獲取子組件實例

  • 選項式API

//父組件

<template>
  <div>
    <Child ref="child" />
  </div>
</template>
<script>
import Child from './Child'
export default {
  components: {
    Child
  },
  mounted(){
    //獲取子組件屬性
    console.log(this.$refs.child.msg) //子組件元素

    //調用子組件方法
    this.$refs.child.childFun('父組件信息')
  }
}
</script>

//子組件 

<template>
  <div>
    <div></div>
  </div>
</template>
<script>
export default {
  data(){
    return {
      msg:'子組件元素'
    }
  },
  methods:{
    childFun(val){
      console.log(`子組件方法被調用,值${val}`)
    }
  }
}
</script>

  • 組合式API

//父組件

<template>
  <div>
    <Child ref="child" />
  </div>
</template>
<script>
import Child from './Child'
import { ref, defineComponent, onMounted } from "vue";
export default defineComponent({
  components: {
    Child
  },

  setup() {
    const child = ref() //註意命名需要和template中ref對應
    onMounted(() => {
      //獲取子組件屬性
      console.log(child.value.msg) //子組件元素

      //調用子組件方法
      child.value.childFun('父組件信息')
    })
    return {
      child //必須return出去 否則獲取不到實例
    }
  },
});
</script>

//子組件

<template>
    <div>
    </div>
</template>
<script>
import { defineComponent, ref } from "vue";
export default defineComponent({
    setup() {
        const msg = ref('子組件元素')
        const childFun = (val) => {
            console.log(`子組件方法被調用,值${val}`)
        }
        return {
            msg,
            childFun
        }
    },
});
</script>

  • setup語法糖

//父組件

<template>
  <div>
    <Child ref="child" />
  </div>
</template>
<script setup>
import Child from './Child'
import { ref, onMounted } from "vue";
const child = ref() //註意命名需要和template中ref對應
onMounted(() => {
  //獲取子組件屬性
  console.log(child.value.msg) //子組件元素

  //調用子組件方法
  child.value.childFun('父組件信息')
})
</script>

//子組件

<template>
    <div>
    </div>
</template>
<script setup>
import { ref,defineExpose } from "vue";
const msg = ref('子組件元素')
const childFun = (val) => {
    console.log(`子組件方法被調用,值${val}`)
}
//必須暴露出去父組件才會獲取到
defineExpose({
    childFun,
    msg
})
</script>

註意

通過ref獲取子組件實例必須在頁面掛載完成後才能獲取。

在使用setup語法糖時候,子組件必須元素或方法暴露出去父組件才能獲取到

EventBus/mitt

兄弟組件通信可以通過一個事件中心EventBus實現,既新建一個Vue實例來進行事件的監聽,觸發和銷毀。

在Vue3中沒有了EventBus兄弟組件通信,但是現在有了一個替代的方案mitt.js,原理還是 EventBus

  • 選項式API
//組件1
<template>
  <div>
    <button @click="sendMsg">傳值</button>
  </div>
</template>
<script>
import Bus from './bus.js'
export default {
  data(){
    return {
      msg:'子組件元素'
    }
  },
  methods:{
    sendMsg(){
      Bus.$emit('sendMsg','兄弟的值')
    }
  }
}
</script>

//組件2

<template>
  <div>
    組件2
  </div>
</template>
<script>
import Bus from './bus.js'
export default {
  created(){
   Bus.$on('sendMsg',(val)=>{
    console.log(val);//兄弟的值
   })
  }
}
</script>

//bus.js

import Vue from "vue"
export default new Vue()

  • 組合式API

首先安裝mitt

npm i mitt -S

然後像Vue2中bus.js一樣新建mitt.js文件

mitt.js

import mitt from 'mitt'
const Mitt = mitt()
export default Mitt

//組件1
<template>
     <button @click="sendMsg">傳值</button>
</template>
<script>
import { defineComponent } from "vue";
import Mitt from './mitt.js'
export default defineComponent({
    setup() {
        const sendMsg = () => {
            Mitt.emit('sendMsg','兄弟的值')
        }
        return {
           sendMsg
        }
    },
});
</script>

//組件2
<template>
  <div>
    組件2
  </div>
</template>
<script>
import { defineComponent, onUnmounted } from "vue";
import Mitt from './mitt.js'
export default defineComponent({
  setup() {
    const getMsg = (val) => {
      console.log(val);//兄弟的值
    }
    Mitt.on('sendMsg', getMsg)
    onUnmounted(() => {
      //組件銷毀 移除監聽
      Mitt.off('sendMsg', getMsg)
    })

  },
});
</script>

  • setup語法糖

//組件1

<template>
    <button @click="sendMsg">傳值</button>
</template>
<script setup>
import Mitt from './mitt.js'
const sendMsg = () => {
    Mitt.emit('sendMsg', '兄弟的值')
}
</script>

//組件2

<template>
  <div>
    組件2
  </div>
</template>
<script setup>
import { onUnmounted } from "vue";
import Mitt from './mitt.js'
const getMsg = (val) => {
  console.log(val);//兄弟的值
}
Mitt.on('sendMsg', getMsg)
onUnmounted(() => {
  //組件銷毀 移除監聽
  Mitt.off('sendMsg', getMsg)
})
</script>


v-model和sync

v-model大家都很熟悉,就是雙向綁定的語法糖。這裡不討論它在input標簽的使用;只是看一下它和sync在組件中的使用

我們都知道Vue中的props是單向向下綁定的;每次父組件更新時,子組件中的所有props都會刷新為最新的值;但是如果在子組件中修改 props ,Vue會向你發出一個警告(無法在子組件修改父組件傳遞的值);可能是為了防止子組件無意間修改了父組件的狀態,來避免應用的數據流變得混亂難以理解。

但是可以在父組件使用子組件的標簽上聲明一個監聽事件,子組件想要修改props的值時使用$emit觸發事件並傳入新的值,讓父組件進行修改。

為了方便vue就使用了v-modelsync語法糖。

  • 選項式API

//父組件

<template>
  <div>
   <!-- 
      完整寫法
      <Child :msg="msg" @update:changePval="msg=$event" /> 
      -->
    <Child :changePval.sync="msg" />
    {{msg}}
  </div>
</template>
<script>
import Child from './Child'
export default {
  components: {
    Child
  },
  data(){
    return {
      msg:'父組件值'
    }
  }
  
}
</script>

//子組件

<template>
  <div>
    <button @click="changePval">改變父組件值</button>
  </div>
</template>
<script>
export default {
  data(){
    return {
      msg:'子組件元素'
    }
  },
  methods:{
    changePval(){
       //點擊則會修改父組件msg的值
      this.$emit('update:changePval','改變後的值')
    }
  }
}
</script>

  • setup語法糖

因為使用的都是前面提過的知識,所以這裡就不展示組合式API的寫法了

//父組件

<template>
  <div>
    <!-- 
      完整寫法
      <Child :msg="msg" @update:changePval="msg=$event" /> 
      -->
    <Child v-model:changePval="msg" />
    {{msg}}
  </div>
</template>
<script setup>
import Child from './Child'
import { ref } from 'vue'
const msg = ref('父組件值')
</script>

//子組件

<template>
    <button @click="changePval">改變父組件值</button>
</template>
<script setup>
import { defineEmits } from 'vue';
const emits = defineEmits(['changePval'])
const changePval = () => {
    //點擊則會修改父組件msg的值
    emits('update:changePval','改變後的值')
}
</script>

總結

vue3中移除了sync的寫法,取而代之的式v-model:event的形式

v-model:changePval="msg"或者:changePval.sync="msg"的完整寫法為
:msg="msg" @update:changePval="msg=$event"

所以子組件需要發送update:changePval事件進行修改父組件的值

路由

vue3和vue2路由常用功能只是寫法上有些區別

  • 選項式API
<template>
  <div>
     <button @click="toPage">路由跳轉</button>
  </div>
</template>
<script>
export default {
  beforeRouteEnter (to, from, next) {
    // 在渲染該組件的對應路由被 confirm 前調用
    next()
  },
  beforeRouteEnter (to, from, next) {
    // 在渲染該組件的對應路由被 confirm 前調用
    next()
  },
  beforeRouteLeave ((to, from, next)=>{//離開當前的組件,觸發
    next()       
  }),
  beforeRouteLeave((to, from, next)=>{//離開當前的組件,觸發
    next()      
  }),
  methods:{
    toPage(){
      //路由跳轉
      this.$router.push(xxx)
    }
  },
  created(){
    //獲取params
    this.$router.params
    //獲取query
    this.$router.query
  }
}
</script>

  • 組合式API
<template>
  <div>
    <button @click="toPage">路由跳轉</button>
  </div>
</template>
<script>
import { defineComponent } from 'vue'
import { useRoute, useRouter } from 'vue-router'
export default defineComponent({
  beforeRouteEnter (to, from, next) {
    // 在渲染該組件的對應路由被 confirm 前調用
    next()
  },
  beforeRouteLeave ((to, from, next)=>{//離開當前的組件,觸發
    next()       
  }),
  beforeRouteLeave((to, from, next)=>{//離開當前的組件,觸發
    next()      
  }),
  setup() {
    const router = useRouter()
    const route = useRoute()
    const toPage = () => {
      router.push(xxx)
    }

    //獲取params 註意是route
    route.params
    //獲取query
    route.query
    return {
      toPage
    }
  },
});
</script>
  • setup語法糖

我之所以用beforeRouteEnter作為路由守衛的示例是因為它在setup語法糖中是無法使用的;大家都知道setup中組件實例已經創建,是能夠獲取到組件實例的。而beforeRouteEnter是再進入路由前觸發的,此時組件還未創建,所以是無法setup中的;如果想在setup語法糖中使用則需要再寫一個setup語法糖的script 如下:

<template>
  <div>
    <button @click="toPage">路由跳轉</button>
  </div>
</template>
<script>
export default {
  beforeRouteEnter(to, from, next) {
    // 在渲染該組件的對應路由被 confirm 前調用
    next()
  },
};
</script>

<script setup>
import { useRoute, useRouter,onBeforeRouteLeave, onBeforeRouteUpdate } from 'vue-router'
const router = useRouter()
const route = useRoute()
const toPage = () => {
  router.push(xxx)
}
//獲取params 註意是route
route.params
//獲取query
route.query

//路由守衛
onBeforeRouteUpdate((to, from, next)=>{//當前組件路由改變後,進行觸發
    next() 
})
onBeforeRouteLeave((to, from, next)=>{//離開當前的組件,觸發
    next() 
})

</script>

寫在最後

通過以上寫法的對比會發現setup語法糖的形式最為便捷而且更符合開發者習慣;未來Vue3的開發應該會大面積使用這種形式。目前Vue3已經成為了Vue的預設版本,後續維護應該也會以Vue3為主;所以還沒開始學習Vue3的同學要抓緊了!

ps:覺得有用的話動動小指頭給個贊吧!!

Vue3文檔地址


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 鏡像下載、功能變數名稱解析、時間同步請點擊 阿裡雲開源鏡像站 **前言:**本文將以 Ubuntu Server 22.04 LTS 為例,說明在 VMware 虛擬機中的安裝和配置 Linux 操作系統的步驟。 一、VMWare 安裝配置 1、VMware 下載地址:VMware Workstation ...
  • Linux管理軟體的三種方法: 包管理 使用倉庫管理 編譯安裝 軟體相關概念: ABI: ABI:Application Binary Interface。應用程式的二進位介面。windows和Linux的二進位格式不一樣(ABI標準不同) Windows與Linux不相容 ELF (Executa ...
  • 雲原生時代需要什麼樣的資料庫?如何構建資料庫服務?騰訊雲資料庫技術負責人程彬認為,雲資料庫未來趨勢會從以托管為核心升級到以極致效率為核心,助力業務降本增效。從資料庫管理和應用角度來看,雲廠商、資源、客戶三角關係背後包含了三個維度的效率:系統效率、運營效率、業務效率,當這些效率都做到極致,成本會大幅下 ...
  • 前言 ​ 所謂的 APP 和 H5 打通,是指 H5 集成 JavaScript 數據採集 SDK 後,H5 觸發的事件不直接同步給伺服器,而是先發給 APP 端的數據採集 SDK,經過 APP 端數據採集 SDK 二次加工處理後存入本地緩存再進行同步。 一、App 與 H5 打通原因 1.1 數據 ...
  • 在各類App都要進行實名制的當下,進行身份認證自然不可避免。平時購買火車票、飛機票,住酒店、打游戲等都需要身份認證,如果每次都要輸入那18位的身份證號十分麻煩,手一抖就會出錯。因此,使用華為機器服務身份證識別功能掃描身份證,錄入身份信息就相當方便了。 1. 業務簡介 HMS Core機器學習服務身份 ...
  • 文本格式化標簽 語義 標簽 加粗 <strong> <b> 傾斜 <em> <i> 刪除線 <del> <s> 下劃線 <ins> <u> 盒子標簽 佈局 <div> 獨占一行,大盒子 <span> 一行可以放多個,小盒子 圖像標簽 <img 屬性=... /> 單標簽 | 屬性 | 屬性值 | 說 ...
  • 這裡給大家分享我在網上總結出來的一些知識,希望對大家有所幫助 一、vue腳手架 1.簡介 Vue CLI 是一個基於 Vue.js 進行快速開發的完整系統。 2.命令行操作步驟 npm install -g @vue/cli 安裝3.x版本的vue腳手架 vue -V 測試是否安裝成功 vue cr ...
  • 函數 函數是 JavaScript 應用程式的基礎,它幫助你實現抽象層,模擬類,信息隱藏和模塊。在 TypeScript 里,雖然已經支持類,命名空間和模塊,但函數仍然是主要的定義行為的地方。TypeScript 為 JavaScript 函數添加了額外的功能,讓我們可以更容易地使用。 基本示例 和 ...
一周排行
    -Advertisement-
    Play Games
  • 概述:在C#中,++i和i++都是自增運算符,其中++i先增加值再返回,而i++先返回值再增加。應用場景根據需求選擇,首碼適合先增後用,尾碼適合先用後增。詳細示例提供清晰的代碼演示這兩者的操作時機和實際應用。 在C#中,++i 和 i++ 都是自增運算符,但它們在操作上有細微的差異,主要體現在操作的 ...
  • 上次發佈了:Taurus.MVC 性能壓力測試(ap 壓測 和 linux 下wrk 壓測):.NET Core 版本,今天計劃準備壓測一下 .NET 版本,來測試並記錄一下 Taurus.MVC 框架在 .NET 版本的性能,以便後續持續優化改進。 為了方便對比,本文章的電腦環境和測試思路,儘量和... ...
  • .NET WebAPI作為一種構建RESTful服務的強大工具,為開發者提供了便捷的方式來定義、處理HTTP請求並返迴響應。在設計API介面時,正確地接收和解析客戶端發送的數據至關重要。.NET WebAPI提供了一系列特性,如[FromRoute]、[FromQuery]和[FromBody],用 ...
  • 原因:我之所以想做這個項目,是因為在之前查找關於C#/WPF相關資料時,我發現講解圖像濾鏡的資源非常稀缺。此外,我註意到許多現有的開源庫主要基於CPU進行圖像渲染。這種方式在處理大量圖像時,會導致CPU的渲染負擔過重。因此,我將在下文中介紹如何通過GPU渲染來有效實現圖像的各種濾鏡效果。 生成的效果 ...
  • 引言 上一章我們介紹了在xUnit單元測試中用xUnit.DependencyInject來使用依賴註入,上一章我們的Sample.Repository倉儲層有一個批量註入的介面沒有做單元測試,今天用這個示例來演示一下如何用Bogus創建模擬數據 ,和 EFCore 的種子數據生成 Bogus 的優 ...
  • 一、前言 在自己的項目中,涉及到實時心率曲線的繪製,項目上的曲線繪製,一般很難找到能直接用的第三方庫,而且有些還是定製化的功能,所以還是自己繪製比較方便。很多人一聽到自己畫就害怕,感覺很難,今天就分享一個完整的實時心率數據繪製心率曲線圖的例子;之前的博客也分享給DrawingVisual繪製曲線的方 ...
  • 如果你在自定義的 Main 方法中直接使用 App 類並啟動應用程式,但發現 App.xaml 中定義的資源沒有被正確載入,那麼問題可能在於如何正確配置 App.xaml 與你的 App 類的交互。 確保 App.xaml 文件中的 x:Class 屬性正確指向你的 App 類。這樣,當你創建 Ap ...
  • 一:背景 1. 講故事 上個月有個朋友在微信上找到我,說他們的軟體在客戶那邊隔幾天就要崩潰一次,一直都沒有找到原因,讓我幫忙看下怎麼回事,確實工控類的軟體環境複雜難搞,朋友手上有一個崩潰的dump,剛好丟給我來分析一下。 二:WinDbg分析 1. 程式為什麼會崩潰 windbg 有一個厲害之處在於 ...
  • 前言 .NET生態中有許多依賴註入容器。在大多數情況下,微軟提供的內置容器在易用性和性能方面都非常優秀。外加ASP.NET Core預設使用內置容器,使用很方便。 但是筆者在使用中一直有一個頭疼的問題:服務工廠無法提供請求的服務類型相關的信息。這在一般情況下並沒有影響,但是內置容器支持註冊開放泛型服 ...
  • 一、前言 在項目開發過程中,DataGrid是經常使用到的一個數據展示控制項,而通常表格的最後一列是作為操作列存在,比如會有編輯、刪除等功能按鈕。但WPF的原始DataGrid中,預設只支持固定左側列,這跟大家習慣性操作列放最後不符,今天就來介紹一種簡單的方式實現固定右側列。(這裡的實現方式參考的大佬 ...