组件与组件之间的通信以及vue2.0中的变化、示例

43 篇文章 0 订阅

一、开始第一个DEMO,其中一个功能需求--组件与组件之间作用域里,但又需要传递数据。

例如:App.vue为父组件,有子组件A.vue、B.vue

1.App的数据传递给A、B

2.A、B的数据传递给App

3.A、B数据相互传递

一、思路

解决以上需求的思路如下:

1.App通过props传递数据给A、B

2.A、B通过$dispatch调用App的Event并传递数据给App

3.A通过$dispatch调用App的Event并传递数据,App通过$broadcast调用B的Event并传递数据

当需要通信的组件是父子关系时,可以使用props、$dispatch、$broadcast传递数据,然而,当需要通信的组件是非父子关系时,他们就需要一个共同的父组件作为介质才能相互传递数据。这时候引入vuex。

参考文章:http://www.html-js.com/article/3663

在vue2.0中

vue2.0

父传子:Props
子传父:子:$emit(eventName) 父$on(eventName)
父访问子:ref
非父子组件通信:https://vuefe.cn/guide/components.html#非父子组件通信
vue2.0 移除:1.$dispatch() 2.$broadcast() 3.events

vue1.0
<template>
  <div id="app">
    <p>{{title}}</p>
    <p v-text="title"></p>
    <p v-text="title2"></p>
    <p v-html="title2"></p>
  </div>
</template>
<script>
export default {
  data () {
    return {
      title: 'this is a title!',
      title2: '<span>?<span> this is a title!'
    }
  }
}
</script>
  • {{title}}v-text="title"等同
  • export default最后生成 new vue({ 参数})
  • 新的ES6写法等同于旧的写法

    //新的ES6
    data () {
    return {
      title: 'this is a title!'
    }
    }
    //旧的写法
    data: function (){
    return {
      title: 'this is a title!'
    }
    }
  • v-html 解析渲染html标签

v-for 及v-bind控制class、v-on绑定事件、v-model双向绑定
<template>
  <div id="app">
    <p>{{title}}</p>
    <!-- <p v-text="title"></p> -->
   <!-- <p v-text="title2"></p> -->
    <!-- <p v-html="title2"></p> -->
    <input v-model="newItem" v-on:keyup.enter="addNew">
    <ul>
      <li v-for = "item in items" v-bind:class="{finished: item.isFinished}" v-on:click="toggleFinished(item)">
        {{item.label}}
      </li>
    </ul>
  </div>
</template>
<script>
import Store from './store'
export default {
  data () {
    return {
      title: 'this is a todolist!',
      title2: '<span>?<span> this is a todolist!',
      items: Store.fetch(),
      newItem: ''
    }
  },
  watch: {
    items: {
      handler (items) {
        Store.save(items)
      },
      deep: true
    }
  },
  methods: {
    toggleFinished (item) {
      item.isFinished = !item.isFinished
    },
    addNew () {
      this.items.push({
        label: this.newItem,
        isFinished: false
      })
      this.newItem = ''
    }
  }
}
</script>

<style>
.finished{
  text-decoration: underline;
}

html {
  height: 100%;
}

body {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
}

#app {
  color: #2c3e50;
  margin-top: -100px;
  max-width: 600px;
  font-family: Source Sans Pro, Helvetica, sans-serif;
  text-align: center;
}

#app a {
  color: #42b983;
  text-decoration: none;
}

.logo {
  width: 100px;
  height: 100px
}
</style>

store.js

const STORAGE_KEY = 'todos-vuejs'
export default {
    fetch () {
        return JSON.parse(window.localStorage.getItem(STORAGE_KEY) || '[]')
    },
    save (items) {
        window.localStorage.setItem(STORAGE_KEY, JSON.stringify(items))
    }
}
  • v-bind:class简写:class
  • v-on:click简写@click
  • v-on:keyup.enter简写@keyup.enter 回车keyup事件
  • v-model 双向绑定
JSON.parse()和JSON.stringify()
  • parse用于从一个字符串中解析出json 对象。例如
    var str='{"name":"cpf","age":"23"}'

经 JSON.parse(str) 得到:

Object: age:"23"
        name:"cpf"
        _proto_:Object

ps:单引号写在{}外,每个属性都必须双引号,否则会抛出异常

  • stringify用于从一个对象解析出字符串,例如

var a={a:1,b:2}

经 JSON.stringify(a)得到:

“{“a”:1,"b":2}”

自定义事件
  • 使用 $on() 监听事件;

  • 使用 $emit()在它上面触发事件;

  • 使用 $dispatch()派发事件,事件沿着父链冒泡;

  • 使用 $broadcast()广播事件,事件向下传导给所有的后代。

父组件向子组件传递
1、采用props

父组件

<component-a msgfromfather='you die!!!!'></component-a>

子组件

<template>
  <div class="hello">
    <h1>{{ msgfromfather }}</h1>
    <button v-on:click="onClickMe">click!</button>
  </div>
</template>

<script>
export default {
  data () {
    return {
    }
  },
  props: ['msgfromfather'],
  methods: {
    onClickMe () {
      console.log(this.msgfromfather)
    }
  }
}
</script>
<style scoped>
h1 {
  color: #42b983;
}
</style>
  • props监听父组件传递过来的信息
  • 传递过来后,可直接引用,就如已经传递过来数据塞到data
2、使用event,$broadcast()从父组件传递消息下去

父组件

<template>
<button v-on:click="talkToMyBoy('be a good boy')">talkToMyBoy</button>
  </div>
</template>
<script>
import Store from './store'
import ComponentA from './components/componentA'
export default {
  components: {
    ComponentA
  },
  methods: {
    talkToMyBoy (msg) {
      //console.log(msg);
      this.$broadcast('onAddnew',msg)
    }
  }
}
</script>

子组件

<template>
  <div class="hello">
    <h1>{{ listentomyfather }}</h1>
  </div>
</template>
<script>
export default {
  data () {
    return {
      listentomyfather: 'Hello from componentA!'
    }
  },
  events: {
    'onAddnew' (msg) {
      //console.log(msg)
      this.listentomyfather = msg
    }
  }
}
</script>
子组件向父组件传递
1.子组件$emit()触发,父组件$on()监听
<template>
  <div class="hello">
    <button v-on:click="onClickMe">telltofather</button>
  </div>
</template>

<script>
export default {
  methods: {
    onClickMe () {
      this.$emit('child-tell-me-something',this.msg)
    }
  }
}
</script>

父组件

<template>
<div id="app">
<p>child tell me: {{childWords}}</p>
<component-a v-on:child-tell-me-something='listenToMyBoy'></component-a>
</div>
</template>

<script>
import Store from './store'
import ComponentA from './components/componentA'
export default {
  components: {
    ComponentA
  },
  data () {
    return {
      childWords: ''
    }
  },
  methods: {
    listenToMyBoy (msg) {
      this.childWords = msg
    }
  }
}
</script>
2.不使用v-on,使用event ,子组件$dispatch(),从子组件传递消息上去

子组件

<template>
  <div class="hello">
    <button v-on:click="onClickMe">talktomyfather</button>
  </div>
</template>

<script>
export default {
  methods: {
    onClickMe () {
      this.$dispatch('child-tell-me-something',this.msg)
    }
  }
}
</script>

父组件

<template>
  <div id="app">
    <p>child tell me: {{childWords}}</p>
    <component-a></component-a>
  </div>
</template>

<script>
import Store from './store'
import ComponentA from './components/componentA'
export default {
  components: {
    ComponentA
  },
  data () {
    return {
      childWords: ''
    }
  },
  events: {
    'child-tell-me-something' (msg) {
      this.childWords = msg
    }
  }
}
</script>


文/_洪小瑶(简书作者)
原文链接:http://www.jianshu.com/p/240125faeb79
著作权归作者所有,转载请联系作者获得授权,并标注“简书作者”。


  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Vue2.0,子组件可以通过props来使用组件传递的数据。父组件在引用子组件的地方,通过给子组件的props属性赋值来传递数据。子组件可以通过props属性接收父组件传递过来的数据,并在子组件内部使用。这样就实现了子组件使用父组件的数据的功能。 具体步骤如下: 1. 在父组件引用子组件,并在子组件的标签上添加props属性,用于接收父组件传递的数据。 2. 在父组件通过v-bind指令或简写语法:来将父组件的数据传递给子组件的props属性。 3. 在子组件,可以通过props属性来访问父组件传递过来的数据,从而使用父组件的数据。 例如,假设父组件的名称为App.vue,子组件的名称为A.vue,我们想要将父组件的name的值传递给子组件A。我们可以在父组件的引用子组件的地方,通过v-bind指令将name的值传递给子组件的props属性。 在父组件App.vue的代码如下: ``` <template> <div> <A :name="name" /> </div> </template> <script> import A from './A.vue'; export default { data() { return { name: 'John', }; }, components: { A, }, }; </script> ``` 在子组件A.vue的代码如下: ``` <template> <div> <p>{{ name }}</p> </div> </template> <script> export default { props: ['name'], }; </script> ``` 通过以上步骤,我们就实现了子组件A使用父组件App的数据name的功能。在子组件A,可以通过props属性来访问父组件传递过来的name值,并在模板使用。 <span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [vue2.0组件给子组件传递数据的方法](https://download.csdn.net/download/weixin_38713167/12764951)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 33.333333333333336%"] - *2* [vue2.0组件改变props值,并向父组件传值的方法](https://download.csdn.net/download/weixin_38626943/12763055)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 33.333333333333336%"] - *3* [Vue2.0三种常用传值方式(父传子、子传父、非父子组件传值)](https://download.csdn.net/download/weixin_38637983/13587439)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 33.333333333333336%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值