在Vue-cli项目中,项目组件间的关系有父子组件和兄弟组件,组件间的传值就是一个经常要用到的知识点,本次就让我们一起看看Vue中 各个组件间是如何实现传值操作的。
为了方便这里我们以App.vue作为父组件
首先了解一下目录结构
第一:父组件向子组件传值
父组件向子组件传值需要用到Props,通过自定义Props的值用v-bind 绑定到子组件标签上的方式传递数据。
父组件代码:
<template>
<div id="app">
<son v-bind:items="cont"></son>
</div>
</template>
<script>
import son from "./components/son.vue";
export default {
name: "App",
data() {
return {
cont:"我是父组件中的数据"
}
},
components: {
son,
},
};
</script>
<style>
#app {
font-family: Avenir, Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
</style>
子组件中的代码:
<template>
<div>
<h1>{{items}}</h1>
</div>
</template>
<script>
export default {
data() {
return {
}
},
props:["items"]
}
</script>
<style>
</style>
子组件用props接受父组件传来的值,并渲染在页面上
子向父传值时就需要用到自定义事件,通过触发子组件自定义的事件向父组件传递数据
子组件内的代码:
<template>
<div>
<h1>{{items}}</h1>
<button @click="aa">点击修改</button>
</div>
</template>
<script>
export default {
data() {
return {
}
},
props:{
items:{
type:String,
default:""
}
},
methods: {
aa(){
this.$emit('changes',"我是被修改的值","我是传递过去的值")
}
},
}
</script>
<style>
</style>
子组件定义了一个 ‘changes’的事件
父组件中:
<template>
<div id="app">
<son :items.sync="cont" @changes="changes"></son>
<son></son>
</div>
</template>
<script>
import son from "./components/son.vue";
export default {
name: "App",
data() {
return {
cont:"我是父组件中的值"
}
},
components: {
son,
},
methods: {
changes(){
this.cont = "我是被修改的数据"
}
},
};
</script>
<style>
#app {
font-family: Avenir, Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
</style>
触发该事件 :
父子组件传值就到这
接下来是兄弟组件间的传值
兄弟组件间的传值需要用到Vue实例中的 $emit 和 $on 方法
main.js中的配置:
import Vue from 'vue'
import App from './App.vue'
Vue.config.productionTip = false
export const eventBus = new Vue(); //用于导出vue实例
new Vue({
render: h => h(App),
}).$mount('#app')
在border组件中 和 son组件中都要引入eventBus 模块
在border组件中:
<template>
<div>
<button @click="cz">border点击向son组件传值</button>
</div>
</template>
<script>
import { eventBus } from "../main";
export default {
data() {
return {
itemss:"我是border组件中的值"
}
},
methods: {
cz(){//向兄弟组件传值方法
eventBus.$emit("eventone",this.itemss)
}
},
created() {
eventBus.$on("cztwo",(num)=>{
console.log(num);
})
},
}
</script>
<style>
</style>
在son组件中:
<template>
<div>
<h1>{{ items }}</h1>
<button @click="aa">点击修改</button><br /><br />
<button @click="cz">son点击向border组件传值</button>
</div>
</template>
<script>
import { eventBus } from "../main";
export default {
data() {
return {
ccc: "我是son组件传递的值",
};
},
props: {
items: {
type: String,
default: "",
},
},
methods: {
aa() {
this.$emit("changes", "我是被修改的值", "我是传递过去的值");
},
cz() {
//向兄弟组件传值方法
eventBus.$emit("cztwo", this.ccc);
},
},
created() {
eventBus.$on("eventone", (num) => {
console.log(num);
});
},
};
</script>
<style>
</style>
效果:
在控制台中 我们看到了兄弟组件中的值已经互相拿到了。
其实在父子组件传值,兄弟组件传值中 还有一个更重要的方法就是利用vuex来进行传值
本期知识点就分享这了,谢谢观看!