VUE组件间常用通讯方式
- 只用于自己复习 谢谢
第一种 父传子
-父
<template>
<div>
<!-- 传递值 -->
<Test
:obj="obj"
info="测试"/>
</div>
</template>
<script>
// 引入子组件
import Test from "../components/Test.vue";
export default {
name: "about",
// 注册子组件
components: {
Test,
},
data() {
return {
obj: { //这个是要传递的数据
code: ,
title: "",
},
};
},
};
</script>
- 子
<template>
<div>
<h1>{{obj.code}}</h1><br>
<h2>{{obj.title}}</h2>
<h3>{{info}}</h3>
</div>
</template>
<script>
export default {
name:'test',
props:{//接收的属性
obj:Object,
info: [String,Number] //info值为其中一种类型即可,其他类型报警告
}
}
</script>
子传父
- 子
<button @click="modifyValue">修改父组件的值</button>
<script>
export default {
name:'test',
methods:{
modifyValue(){
this.$emit('modify','子组件传递过来的值')
}
}
}
</script>
- 父
<Test
:obj="obj"
info="测试"
@modify="modifyFatherValue"/>
<script>
// 引入子组件
import Test from "../components/Test.vue";
export default {
name: "about",
// 注册子组件
components: {
Test,
},
data() {
return {
msg:'我是父组件'
};
},
methods:{
// 接受子组件传递来的值,赋值给data中的属性
modifyFatherValue(e){
this.msg = e
}
}
};
</script>
使用vuex进行组件间的通讯
- VUEX
- 通过dispatch 调用到actions(可以用来调用后端api) 然后commit 然后mutations state
- 可以在组件中直接调用commit
- npm i vuex 在vue2中安装 npm i vuex@3
- vue.use(vuex)
import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);
//从action -》 mutations -》 state
export default new Vuex.Store({
state: { //用来存放内容的地方
sharedData: 'Global State'
},
mutations: {
updateSharedData(state, newData) {
state.sharedData = newData;
}
},
actions: {
updateData({ commit }, newData) {
commit('updateSharedData', newData);//commit回去调用mutations中方法
}
},
getters: {
getSharedData(state) {//这个就是可以对数据进行去处理 计算属性
return state.sharedData;
}
}
});
- this.$store.dispatch()
- 如果action中没有业务逻辑 就可以直接调用 this.$strore.commit(‘jia’,)
- 插值语法 直接使用{{store.value}}
- {{$store.getters.bigSum}}
- 优化$store 直接使用属性名来进行操作数据 批量生成
<script>
import { mapState, mapActions } from 'vuex';
export default {
computed: {
...mapState(['sharedData']) //这个是数据 从state中读取数据
...mapGetters([]) //从getter获取数据
},
methods: {
...mapActions(['updateData'])//就是从action中直接调用方法
...mapMutations([]) //mutations调用方法 this.$store.commit 相当于这个方法
},
mounted() {
this.updateData('Updated Global State');
console.log(this.sharedData);
}
};
</script>