父到子:
- father.vue中:
<router-view :data="d" msg="hello"></router-view>
data() {
return {
d: "發送給兄弟的數據"
};
},
- son.vue中:(在export defaullt內部添加屬性props)
props: ["data","msg"]
然後就可以在子組件中直接使用{{data}}
<h1>{{ data }} {{msg}}</h1>
子到父:
- son.vue中:
data() {
return {
msg: "傳給父組件"
};
},
mounted() {
this.$emit("toparent", this.msg); //傳遞數據給父組件
}
- father.vue中:
<router-view @toparent="get"/>
data() {
return {
msg: "原來的數據"
};
},
methods: {
get(a) {
this.msg = a;
}
},
兄弟組件傳值:
- 在main.js中,new一個空的vue掛在到vue原型上(需要在創建Vue實例之前掛載):
Vue.prototype.$bus = new Vue();
- 在demo.vue中使用bus發送數據(可以通過點擊事件觸發)
this.$bus.$emit("sendData",{data:"需要發送的數據"})
- 在另一個test.vue中接收數據(可以寫在created生命週期函數中)
this.$bus.$on("sendData",d=>{console.log(d)})
祖孫組件傳值:可以跨多級組件傳遞數據
- grandparent.vue中:
export default {
name: "home",
provide(){
return {
msg:"來自祖先的數據",
fn(){console.log("祖先的方法")}
}
},
}
- son.vue中:
<div>{{msg}}</div>
export default {
name: "detail",
inject:["msg","fn"]
}
注意:provide提供的值不能修改,只能訪問!!!但是可以通過provide中的方法去改變data屬性中的值,可以看這個小應用:傳送門
其他傳值方式:
1. 子獲取父的值:直接在子組件中this.$parent.msg即可獲取到父組件的值,可以修改,但是不推薦這種方式修改
2. 父獲取子的值:在father.vue中,也可以修改子組件的數據,但不推薦
<router-view ref="child"/>
mounted() {
console.log(this.$refs.child.msg); //主動獲取子組件的數據
}
3.main.js中的根構造函數中的data可以作爲全局數據管理,可以對數據進行操作,this.$root.XXX訪問即可,$root也能訪問到method裏面的方法.小型項目可以使用該方式,大項目推薦使用vuex
//main.js
new Vue({
data: {
gdata: 6
},
methods: {
setData() {
console.log("testFn");
}
},
router,
store,
render: h => h(App)
}).$mount("#app");
//test.vue
mounted() {
this.$root.gdata += 1;
this.$root.setData();
console.log(this.$root.gdata);
}
4. 使用vuex傳值:傳送門
5. 另外也可以使用localStorage,sessionStorage, cookie傳遞數據