Vue.js父与子组件之间传参 Vue.js父与子组件之间传参

Vue.js父与子组件之间传参

父向子组件传参

  例子:App.vue为父,引入helloWord组件之后,则可以在template中使用标签(注意驼峰写法要改成hello-word写法,因为html对大小写不敏感,hello-word与helloWord对于它来说是一样的,不好区分,所以使用小写-小写这种写法)。而子组件helloWord中,声明props参数’msgfromfa’之后,就可以收到父向子组件传的参数了。例子中将msgfromfa显示在<p>标签中。
App.vue中

<hello-word msgfromfa="(Just Say U Love Me)"></hello-word>

import helloWord from './components/helloWord'

export  default  {
  new  Vue({
    components: {
      helloWord
    }
  })
}
 
helloWord.vue中 :
<p>{{ msgfromfa }}</p>
<script>  
export default {
  props: ['msgfromfa']
}
</script>

父向子组件传参(.$broadcast)

  用法:vm.$broadcast( event, […args] )广播事件,通知给当前实例的全部后代。因为后代有多个枝杈,事件将沿着各“路径”通知。
  例子:父组件App.vue中<input>绑定了键盘事件,回车触发addNew方法,广播事件”onAddnew”,并传参this.items。子组件helloWord中,注册”onAddnew”事件,打印收到的参数items。
App.vue中

<div id="app">
  <input v-model="newItem" @keyup.enter="addNew"/>
</div>
import helloWord from './components/helloWord'
export default {
  new Vue({
    methods: {
      addNew: function() {
        this.$broadcast('onAddnew', this.items)
        }
      }
    })
}
helloWord.vue中
import helloWord from './components/helloWord'
 export default {
  events: {
    'onAddnew': function(items){
      console.log(items)
      }
    }
 }

子组件向父传参(.$emit)

  用法:vm.$emit( event, […args] ),触发当前实例上的事件。附加参数都会传给监听器回调。
  例子:App.vue中hello-Word绑定了自定义事件”child-say”。子组件helloWord中,单击按钮后触发”child-say”事件,并传参msg给父组件。父组件中listenToMyBoy方法把msg赋值给childWords,显示在<p>标签中。

App.vue中

<p>Do you like me? {{childWords}}</p>
<hello-Word msgfromfa="(Just Say U Love Me)" v-on:child-say="listenToMyBoy"></hello-Word>
import helloWord from './components/helloWord'
export default { 
new Vue({
  data: function () {
    return {
      childWords: ""
    }
   },
  components: { helloWord },
  methods: {
    listenToMyBoy: function (msg){
      this.childWords = msg
      }
     }
  })
}
componentA.vue中 
<button v-on:click="onClickMe">like!</button>
import helloWord from './components/helloWord'
export default { data: function () { return { msg: 'I like you!' } }, methods: { onClickMe: function(){ this.$emit('child-say',this.msg); } } }
 

子组件向父传参(.$dispatch)

 

  用法:vm.$dispatch( event, […args] ),派发事件,首先在实例上触发它,然后沿着父链向上冒泡在触发一个监听器后停止。
  例子:App.vue中events中注册”child-say”事件。子组件helloWord中,单击按钮后触发”child-say”事件,并传参msg给父组件。父组件中”child-say”方法把msg赋值给childWords,显示在<p>标签中。
App.vue中

 
<p>Do you like me? {{childWords}}</p>
<hello-Word msgfromfa="(Just Say U Love Me)"></hello-Word>
import helloWord from './components/helloWord'
export default { new Vue({ events: { 'child-say' : function(msg){ this.childWords = msg } } }) }
componentA.vue中 
<button v-on:click="onClickMe">like!</button>
import helloWord from './components/helloWord'
export default { data: function () { return { msg: 'I like you!' } }, methods: { onClickMe: function(){ this.$dispatch('child-say',this.msg); } } }
 

猜你喜欢

转载自www.cnblogs.com/tianyou-songshao/p/9105359.html