vue中父子組件傳值

vue中父子組件傳值是經(jīng)常使用的場(chǎ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)用

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容