一.基本傳值方法 props/$emit
首先,我們從組件開始,導(dǎo)入子組件(進(jìn)行注冊(cè)).
import recruitSwiper from "@/components/recruit/recruit-swiper.vue"
export default {
components: {
recruitItem
},
data() {
return {}
}
}
將注冊(cè)好的子組件應(yīng)用至父組件,通過屬性綁定 :info="xxx",進(jìn)行 父>子 值傳遞
<recruitItem :info="xxx"></recruitItem>
到子組件里面,用 props 接收
export default {
props: {
Info: {
type: Array
}
}
}
//接下來進(jìn)行遍歷即可
<block v-for="(info,index) in Info" :key="index"></block>
子組件向父組件傳值,要運(yùn)用 $emit 進(jìn)行發(fā)射
export default {
props: {
Info: {
type: Array
}
},
methods: {
sendTask(e) {
this.$emit("sendTask", e) // (方法名,參數(shù))
}
}
}
接收之前定義的方法名 (sendTask)
<recruit-item :info="xxx" @sendTask="sendTask"></recruit-item>
//這里定義方法
methods: {
sendTask(e) {
console.log(e)
}
}
這就是基本的父子組件傳值了.
二.vuex傳值
首先使用npm進(jìn)行安裝
npm i vuex -g
npm i vuex -S
靜態(tài)目錄src下新建一個(gè)sotre/index.js這就是你的倉庫了
import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex)
const store = new Vuex.Store({
state: {
url: "xxx"
},
getters: {},
mutations: {},
modules: {}
})
export default store;
入口文件mian.js進(jìn)行全局注冊(cè),現(xiàn)在就綁在vue原型上了
import store from './store'
Vue.prototype.$store = store;//后面可以直接使用 this.$store
};
改變url的值,直接改this.$store.state.url="new",可以變化.但根據(jù)官方說法,最好使用commit進(jìn)行值的變更.
// store/index.js
const store = new Vuex.Store({
state: {
url: "xxx"
},
mutations: {
setUrl(state,value) {
state.url = value // 變更
}
})
export default store;
//sub.vue
this.$store.state.url //值的獲取
this.$store.commit("setUrl","newUrl") //值的更改
三.在Vue的屬性綁定:bind中,綁定的類型不僅僅是數(shù)組/對(duì)象等.也可以是函數(shù),例如一下例子;
下述方法主要運(yùn)用過程,父組件中傳遞給子組件函數(shù)方法,子組件調(diào)用.
// 父組件
<template>
<div :useFunction="usedFunction"></div>
</template>
<script>
data(){
return{
name:'xixi'
}
},
methods(){
useFunction(request){
this.name = request;
}
}
</script>
// 子組件
<template>
<div @click="useModule"></div>
</template>
<script>
props:{
usedFunction:{
type:Function
}
},
methods(){
useModule(){
this.usedFunction('test')
}
}
</script>