Vue組件傳參11種方式舉例介紹
1. props 和 emit
vue2
父組件
<son count="100" @addCount = "addCount"></son>
addCount(val) {}子組件
props: ['count'] // [{count: Number}] [{count: {type: Number, default: 0}],this.$emit('addCount', value)vue3
父組件
<son count="100" @addCount = "addCount"></son>
constaddCount = (val) => {}子組件
const props = defineProps(['count']) // defineProps({ count: Number })
defineProps<{ count?: number }>(),const emit = defineEmits(['addCount'])
functionbuttonClick() {
emit('addCount')
}2. $attrs 和 $listeners
$attrs // 組件傳值, 除了已在prop聲明的值和 class樣式名 style行內(nèi)樣式
$listeners // 組件傳函數(shù), 除了.native// 父組件
<Son :num="num" @addNum='addNum'></Son>
// 子組件
<GrandSon></GrandSon><div>{{$attrs.num}}</div>
// 孫子組件
<div @click="clickFn">{{$attrs.num}}</div>methods:{
clickFn(){
this.$listeners.addNum()
}
}3. v-model
vue2
vue2 v-mode 是 :value="msg" @input="msg=$event" 的語(yǔ)法糖
父組件
<TabsVue v-model="activeComponent" />
子組件
props:{
activeComponent:{
type:string,
default:''
}
}
this.$emit('update:activeComponent',value)vue3
vue3 v-mode 是 :modelValue="msg" @update:modelValue="msg=$event" 的語(yǔ)法糖
父組件
<TabsVue v-model:activeComponent="activeComponent" />
子組件
const props = defineProps({
activeComponent: {
type: String,
default: '庫(kù)存信息',
},
});
const emit = defineEmits(['update:activeComponent']);
functiontabsChange(index: number) {
activeIndex.value = index;
emit('update:activeComponent', props.data[index]);
}4. 作用域插槽
<template>
<div>
<!--默認(rèn)插槽-->
<slot></slot>
<!--另一種默認(rèn)插槽的寫法-->
<slot name="default"></slot>
<!--具名插槽-->
<slot name="footer"></slot>
<!--作用域插槽-->
<slot v-bind:user="user" name="header"></slot>
</div>
</template>
<!--使用-->
<children>
<!--跑到默認(rèn)插槽中去-->
<div>123</div>
<!--另一種默認(rèn)插槽的寫法-->
<template v-slot:default></template>
<!--跑到具名插槽 footer 中去-->
<template v-slot:footer></template>
<!--縮寫形式-->
<template #footer></template>
<!--獲取子組件的值-->
<template v-slot:header="slot">{{slot.user}}</template>
<!--結(jié)構(gòu)插槽值-->
<template v-slot:header="{user: person}">{{person}}</template>
<!--老式寫法,可以寫到具體的標(biāo)簽上面-->
<template slot="footer" slot-scope="scope"></template>
</children>5. $refs, $root, $parent, $children
$root 獲取根組件
$parent 獲取父組件
$children 獲取子組件(所有的子組件,不保證順序)
$refs 組件獲取組件實(shí)例,元素獲取元素
6. provide 和 inject
vue2
父組件
provide(){
return{
color:this.color
}
}子孫組件
<h3>{color}</h3>
exportdefault{
inject:['color'] //inject: { color: 'color' } inject: {color: {from: 'colorcolor',default:#333}}
}vue3
父組件
import { provide } from'vue';
provide('money',money)
provide('changeMoneyFn',number=>{
money.value-=number
})子孫組件
import { inject } from"vue";
const money =inject('money')
const changeMoneyFn=inject('changeMoneyFn')7. mitt/ event-bus
event-bus
/* eventbus.js 暴露總結(jié)總線文件 */// 這里我們?cè)趈s中暴露這個(gè)事件總線對(duì)象 import Vue from 'vue' export default new Vue()
// 注冊(cè)事件
bus.$on("getScore", data => {
this.yoursore = data;
});
// 觸發(fā)事件
bus.$emit("getScore", this.score);mitt
/* eventbus.js 暴露總結(jié)總線文件 */// 這里我們?cè)趈s中暴露這個(gè)事件總線對(duì)象 import mitt from"mitt"; const emitter = mitt(); exportdefault emitter;
// 注冊(cè)事件import emitter from"./utils/eventbus.js";
emitter.on("getScore", data => {
this.yoursore = data;
});
// 觸發(fā)事件import emitter from"./utils/eventbus.js";
emitter.emit("getScore", this.score)8. pina/vuex
vuex
聲明
import { createApp } from'vue'import { createStore } from'vuex'// 創(chuàng)建一個(gè)新的 store 實(shí)例const store = createStore({
state () {
return {
count: 0
}
},
mutations: {
increment (state) {
state.count++
}
},
actions: {},
getters: {},
modules: {}
})
const app = createApp({ /* 根組件 */ })
// 將 store 實(shí)例作為插件安裝
app.use(store)使用
1. 直接調(diào)用
this.$store.state.name// 跨模塊訪問(wèn) state 數(shù)據(jù): store.rootState.user.profile.tokenthis.$store.commit('setCount', 5) // 跨模塊訪問(wèn)mutation方法 : store.commit('permission/setRoutes', [], { root: true })this.$store.dispatch("asyncSetCount", 5)
this.$store.getters.validList2. 計(jì)算屬性調(diào)用
computed: {
name(){
returnthis.$store.state.name;
},
validList(){
returnthis.$store.getters.validList;
}
}
3. 方法調(diào)用
4. 引入輔助函數(shù), 延展運(yùn)算符展開調(diào)用
import { mapState, mapMutations, mapActions, mapGetters } from'vuex'computed: { ...mapState(['name']), ...mapGetters(['validList']) }
methods: { ...mapMutations(['setCount']), ...mapActions(['asyncSetCount']) }
5. 模塊化調(diào)用
import { mapMutations } from'vuex'this.$store.state.user.tokenthis.$store.commit('user/setNewState', 666)
methods: {
...mapMutations(["user/setNewState"]),
setNewState(data) {
this['user/setNewState'](data)
}
}
6. createNamespacedHelpers 創(chuàng)建基于某個(gè)命名空間輔助函數(shù)
import { createNamespacedHelpers, mapGetters } from"vuex";
const { mapMutations } = createNamespacedHelpers("user");
exportdefault {
computed: {
...mapGetters(["token", "name"]),
},
methods: {
...mapMutations(["setNewState"]),
},
};
< h3 > name: { { name } }< /h3>
< button @click="setNewState(666)" > 修改數(shù)據(jù) < /button >pina
聲明
import { createPinia } from'pinia'
app.use(createPinia())import { defineStore } from'pinia'// useStore 可以是 useUser、useCart 之類的任何東西// 第一個(gè)參數(shù)是應(yīng)用程序中 store 的唯一 idexportconst useStore = defineStore('main', {
state: () => {
return {
// 所有這些屬性都將自動(dòng)推斷其類型counter: 0,
}
},
getters: {
doubleCount: (state) => state.counter * 2,
},
actions: {
increment() {
this.counter++
},
},
})使用
import { useStore } from'@/stores/counter'const store = useStore()
const { counter, doubleCount } = storeToRefs(store)
store.$reset() // 將狀態(tài) 重置 到其初始值
store.counter++
store.$patch({
counter: store.counter + 1,
})
store.$state = { counter: 666 }
pinia.state.value = {}9. 路由傳參
this.$router 相當(dāng)于一個(gè)全局的路由器對(duì)象,包含了很多屬性和對(duì)象(比如 history 對(duì)象),任何頁(yè)面都可以調(diào)用其 push(), replace(), go() 等方法。
跳轉(zhuǎn)帶參
//字符串this.$router.push('home')
//對(duì)象this.$router.push({path:'/user/${userId}'})
//命名的路由this.$router.push({name:'user', params:{userId: '123'}})
//帶查詢參數(shù),變成 /register?plan=privatethis.$router.push({path:'register', query:{plan:private}})this.$route 表示當(dāng)前路由對(duì)象,每一個(gè)路由都會(huì)有一個(gè) route 對(duì)象,是一個(gè)局部的對(duì)象,可以獲取對(duì)應(yīng)的 name, path, params, query 等屬性。
params
1. router-link導(dǎo)航aaaa
父組件 <router-link to="/child/123">
</router-link>
子組件 this.$route.params.num
路由配置 {path:'/child/:num',name:'child',component:Child}
地址欄 /child/123 顯示參數(shù),刷新不丟失
2.$router.push跳轉(zhuǎn)
父組件
<li @click='this.$router.push({path:'/child/${itemId}'})'> </li>
子組件 this.$route.params.id
路由配置 {path:'/child/:id',name:'child',component:Child}
地址欄 /child/1 顯示參數(shù),刷新不丟失
3.通過(guò)name確定路由,params傳參
父組件
<li @click='this.$router.push({name:'child',params:{id:1}})'> </li>
子組件 this.$route.params.id
路由配置 {path:'/child',name:'child',component:Child}
地址欄 /child 不顯示參數(shù),刷新丟失query
1.path匹配路由,通過(guò)query傳參
父組件
<li @click='this.$router.push({path:'/child',query:{id:1}})'> </li>
子組件 this.$route.query.id
路由配置 {path:'/child',name:'child',component:Child}
地址欄 /child?id=1 顯示參數(shù),刷新不丟失path
獲取當(dāng)前路由地址 this.$route.path
meta
獲取路由meta屬性值 this.$route.meta
10. 全局變量
將屬性掛載到window對(duì)象
window.myName = 'fish'// window['mayName'] = 'fish'
11. 本地存儲(chǔ)
LocalStorage
// 存儲(chǔ)數(shù)據(jù)localStorage.setItem("info",JSON.stringify(info));
// 獲取數(shù)據(jù)const info = JSON.parse(localStorage.getItem("info"));
// 移除數(shù)據(jù)localStorage.removeItem("info");
// 清除localStorage.clear()SessionStorage
// 存儲(chǔ)數(shù)據(jù)
sessionStorage.setItem("info",JSON.stringify(info));
// 獲取數(shù)據(jù)const info = JSON.parse(sessionStorage.getItem("info"));
// 移除數(shù)據(jù)
sessionStorage.removeItem("info");
// 清除
sessionStorage.clear()總結(jié)
到此這篇關(guān)于Vue組件傳參11種方式的文章就介紹到這了,更多相關(guān)Vue組件傳參方式內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
ssm+vue前后端分離框架整合實(shí)現(xiàn)(附源碼)
這篇文章主要介紹了ssm+vue前后端分離框架整合實(shí)現(xiàn)(附源碼),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2020-07-07
vue頁(yè)面引入three.js實(shí)現(xiàn)3d動(dòng)畫場(chǎng)景操作
這篇文章主要介紹了vue頁(yè)面引入three.js實(shí)現(xiàn)3d動(dòng)畫場(chǎng)景操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-08-08
用npm安裝vue和vue-cli,并使用webpack創(chuàng)建項(xiàng)目的方法
今天小編就為大家分享一篇用npm安裝vue和vue-cli,并使用webpack創(chuàng)建項(xiàng)目的方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2018-09-09
Vue前端數(shù)值轉(zhuǎn)換為千分位格式并保留兩位小數(shù)代碼示例
在Vue.js開發(fā)中我們經(jīng)常會(huì)遇到需要將數(shù)字格式化為保留兩位小數(shù)的情況,下面這篇文章主要給大家介紹了關(guān)于Vue前端數(shù)值轉(zhuǎn)換為千分位格式并保留兩位小數(shù)的相關(guān)資料,需要的朋友可以參考下2024-06-06
Vue axios與Go Frame后端框架的Options請(qǐng)求跨域問(wèn)題詳解
這篇文章主要介紹了Vue axios與Go Frame后端框架的Options請(qǐng)求跨域問(wèn)題詳解,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2020-03-03
Vue利用Mixin輕松實(shí)現(xiàn)代碼復(fù)用
Mixin,中文翻譯為"混入",在Vue中是一種非常有用的功能,可以解決許多開發(fā)中的常見問(wèn)題,下面就讓我們一起深入了解一下Mixin在Vue中解決了哪些問(wèn)題吧2023-06-06
vue + element ui實(shí)現(xiàn)播放器功能的實(shí)例代碼
這篇文章主要介紹了vue + element ui實(shí)現(xiàn)播放器功能,本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2021-04-04
Vue3報(bào)錯(cuò)Cannot convert undefined or null&n
Vue3與Vue-cli5中出現(xiàn)“Cannot convert undefined or null to object”錯(cuò)誤,因基類組件data()未返回默認(rèn)空值對(duì)象導(dǎo)致屬性合并異常,解決方法是確保data()返回對(duì)象,避免繼承組件屬性沖突2025-08-08

