最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Vue組件傳參11種方式舉例介紹

 更新時間:2023年09月04日 11:22:44   作者:前端黃大仙  
這篇文章主要給大家介紹了關(guān)于Vue組件傳參11種方式的相關(guān)資料,文中通過代碼示例介紹的非常詳細,對大家學(xué)習(xí)或者使用vue具有一定的參考借鑒價值,需要的朋友可以參考下

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" 的語法糖

父組件

<TabsVue v-model="activeComponent" />

子組件

props:{
    activeComponent:{
        type:string,
        default:''
    }
}
this.$emit('update:activeComponent',value)

vue3

vue3 v-mode 是 :modelValue="msg" @update:modelValue="msg=$event" 的語法糖

父組件

<TabsVue v-model:activeComponent="activeComponent" />

子組件

const props = defineProps({
    activeComponent: {
        type: String,
        default: '庫存信息',
    },
});
const emit = defineEmits(['update:activeComponent']);
functiontabsChange(index: number) {
    activeIndex.value = index;
    emit('update:activeComponent', props.data[index]);
}

4. 作用域插槽

<template>
    <div>
        <!--默認插槽-->
        <slot></slot>
        <!--另一種默認插槽的寫法-->
        <slot name="default"></slot>
        <!--具名插槽-->
        <slot name="footer"></slot>
        <!--作用域插槽-->
        <slot v-bind:user="user" name="header"></slot>
    </div>
</template>
<!--使用-->
<children>
    <!--跑到默認插槽中去-->
    <div>123</div>
    <!--另一種默認插槽的寫法-->
    <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>
    <!--老式寫法,可以寫到具體的標簽上面-->
    <template slot="footer" slot-scope="scope"></template>
</children>

5. $refs, $root, $parent, $children

  • $root 獲取根組件

  • $parent 獲取父組件

  • $children 獲取子組件(所有的子組件,不保證順序)

  • $refs 組件獲取組件實例,元素獲取元素

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é)總線文件 */// 這里我們在js中暴露這個事件總線對象 
import Vue from 'vue'
export default new Vue()
// 注冊事件
bus.$on("getScore", data => {
    this.yoursore = data;
});
// 觸發(fā)事件
bus.$emit("getScore", this.score);

mitt

/* eventbus.js 暴露總結(jié)總線文件 */// 這里我們在js中暴露這個事件總線對象 import mitt from"mitt"; 
const emitter = mitt(); 
exportdefault emitter;
// 注冊事件import emitter from"./utils/eventbus.js";
emitter.on("getScore", data =&gt; {
    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)建一個新的 store 實例const store = createStore({
  state () {
    return {
      count: 0
    }
  },
  mutations: {
    increment (state) {
      state.count++
    }
  },
  actions: {},
  getters: {},
  modules: {}
})
const app = createApp({ /* 根組件 */ })
// 將 store 實例作為插件安裝
app.use(store)

使用

1. 直接調(diào)用
this.$store.state.name// 跨模塊訪問 state 數(shù)據(jù): store.rootState.user.profile.tokenthis.$store.commit('setCount', 5) // 跨模塊訪問mutation方法 : store.commit('permission/setRoutes', [], { root: true })this.$store.dispatch("asyncSetCount", 5)
this.$store.getters.validList2. 計算屬性調(diào)用
computed: { 
  name(){ 
    returnthis.$store.state.name; 
  },
  validList(){ 
    returnthis.$store.getters.validList;
  }
}
3. 方法調(diào)用
4. 引入輔助函數(shù), 延展運算符展開調(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)建基于某個命名空間輔助函數(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 之類的任何東西// 第一個參數(shù)是應(yīng)用程序中 store 的唯一 idexportconst useStore = defineStore('main', {
 state: () => {
    return {
      // 所有這些屬性都將自動推斷其類型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)于一個全局的路由器對象,包含了很多屬性和對象(比如 history 對象),任何頁面都可以調(diào)用其 push(), replace(), go() 等方法。

跳轉(zhuǎn)帶參
//字符串this.$router.push('home')
//對象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)前路由對象,每一個路由都會有一個 route 對象,是一個局部的對象,可以獲取對應(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.通過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匹配路由,通過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對象

window.myName = 'fish'// window['mayName'] = 'fish'

11. 本地存儲

LocalStorage

// 存儲數(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

// 存儲數(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)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • ssm+vue前后端分離框架整合實現(xiàn)(附源碼)

    ssm+vue前后端分離框架整合實現(xiàn)(附源碼)

    這篇文章主要介紹了ssm+vue前后端分離框架整合實現(xiàn)(附源碼),文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2020-07-07
  • Vue3?中的ref與props屬性詳解

    Vue3?中的ref與props屬性詳解

    這篇文章主要介紹了Vue3?中的ref與props屬性知識,本文通過實例代碼給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友參考下吧
    2025-04-04
  • vue頁面引入three.js實現(xiàn)3d動畫場景操作

    vue頁面引入three.js實現(xiàn)3d動畫場景操作

    這篇文章主要介紹了vue頁面引入three.js實現(xiàn)3d動畫場景操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2020-08-08
  • 用npm安裝vue和vue-cli,并使用webpack創(chuàng)建項目的方法

    用npm安裝vue和vue-cli,并使用webpack創(chuàng)建項目的方法

    今天小編就為大家分享一篇用npm安裝vue和vue-cli,并使用webpack創(chuàng)建項目的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2018-09-09
  • Vue前端數(shù)值轉(zhuǎn)換為千分位格式并保留兩位小數(shù)代碼示例

    Vue前端數(shù)值轉(zhuǎn)換為千分位格式并保留兩位小數(shù)代碼示例

    在Vue.js開發(fā)中我們經(jīng)常會遇到需要將數(shù)字格式化為保留兩位小數(shù)的情況,下面這篇文章主要給大家介紹了關(guān)于Vue前端數(shù)值轉(zhuǎn)換為千分位格式并保留兩位小數(shù)的相關(guān)資料,需要的朋友可以參考下
    2024-06-06
  • Vue axios與Go Frame后端框架的Options請求跨域問題詳解

    Vue axios與Go Frame后端框架的Options請求跨域問題詳解

    這篇文章主要介紹了Vue axios與Go Frame后端框架的Options請求跨域問題詳解,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2020-03-03
  • Vue利用Mixin輕松實現(xiàn)代碼復(fù)用

    Vue利用Mixin輕松實現(xiàn)代碼復(fù)用

    Mixin,中文翻譯為"混入",在Vue中是一種非常有用的功能,可以解決許多開發(fā)中的常見問題,下面就讓我們一起深入了解一下Mixin在Vue中解決了哪些問題吧
    2023-06-06
  • vue + element ui實現(xiàn)播放器功能的實例代碼

    vue + element ui實現(xiàn)播放器功能的實例代碼

    這篇文章主要介紹了vue + element ui實現(xiàn)播放器功能,本文通過實例代碼給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2021-04-04
  • 淺談vuex中store的命名空間

    淺談vuex中store的命名空間

    今天小編就為大家分享一篇淺談vuex中store的命名空間,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2019-11-11
  • Vue3報錯Cannot convert undefined or null to object問題及解決

    Vue3報錯Cannot convert undefined or null&n

    Vue3與Vue-cli5中出現(xiàn)“Cannot convert undefined or null to object”錯誤,因基類組件data()未返回默認空值對象導(dǎo)致屬性合并異常,解決方法是確保data()返回對象,避免繼承組件屬性沖突
    2025-08-08

最新評論

报价| 正宁县| 措勤县| 大冶市| 东海县| 龙岩市| 阜新市| 乐平市| 交口县| 宜宾市| 夏河县| 三河市| 嘉义县| 措勤县| 祁门县| 湘阴县| 霸州市| 裕民县| 通江县| 马鞍山市| 尼勒克县| 弋阳县| 连云港市| 西藏| 普兰县| 苏尼特左旗| 育儿| 寿阳县| 土默特右旗| 曲水县| 普格县| 麦盖提县| 时尚| 河曲县| 杭锦后旗| 黎平县| 吉林市| 增城市| 鹰潭市| 滦南县| 策勒县|