vue中父子組件傳值是經(jīng)常使用的場景
父組件向子組件中傳值
父組件
<template>
<div id="app">
<img alt="Vue logo" src="./assets/logo.png">
<HelloWorld @changeAge="changeAge" :age="age" :name="name" msg="Welcome to Your Vue.js App"/>
</div>
</template>
<script>
import HelloWorld from './components/HelloWorld.vue'
export default {
name: 'app',
data: ()=>{
return {
name:"liuhao",
age:29
}
},
methods:{
changeAge(){
this.age++
}
},
components: {
HelloWorld
}
}
</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 class="hello">
<h1>{{ msg }}</h1>
<h2 class="red">{{ name }}:{{age}}</h2>
<button @click="changeAge()">修改數(shù)據(jù)</button>
<button @click="$emit('changeAge')">修改數(shù)據(jù)</button>
</div>
</template>
<script>
export default {
name: 'HelloWorld',
props: ["msg","name","age"],
methods:{
changeAge(){
this.$parent.changeAge()
}
}
}
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
h3 {
margin: 40px 0 0;
}
ul {
list-style-type: none;
padding: 0;
}
li {
display: inline-block;
margin: 0 10px;
}
a {
color: #42b983;
}
.red{
color:#f3927f
}
</style>
父組件向子組件中傳值分三步
1对湃、在父組件中給子組件命名屬性芯杀,通過該屬性向子組件傳值
2崭放、子組件需要事先在props中聲明該屬性名电禀,這樣才能接收父組件傳過來的值
3边篮、在子組件中直接調(diào)用屬性名己莺,該屬性便是父組件傳過來的屬性值
子組件傳值給父組件有兩種方法
一、第一種
1戈轿、在父組件中定義方法凌受,并通過@+方法名
的方式告知子組件傳過去的方法名
2、在子組件中通過$emit(方法名思杯,參數(shù)...)
調(diào)用父組件傳過來的方法
二胜蛉、第二種
1、在父組件中定義方法色乾,并通過@+方法名
的方式告知子組件傳過去的方法名
2誊册、在子組件中通過this.$parent.方法名()
調(diào)用